It is hard to do, since the ranges are not equally distributed, and there is no data for all intervals.But here is the first approach-- prepare test datadeclare @test table (Name varchar, age tinyint)insert @testselect 'A', 15 union allselect 'B', 18 union allselect 'C', 22 union allselect 'D', 27 union allselect 'E', 33 union allselect 'F', 42-- do the workselect * from @testselect convert(varchar, 10 * (age / 10)) + '-' + convert(varchar, 9 + 10 * (age / 10)) Range, count(*) Countfrom @testgroup by convert(varchar, 10 * (age / 10)) + '-' + convert(varchar, 9 + 10 * (age / 10))
Here is the second approach-- do the work again thus semi-hardwiredSELECT z.Range, COUNT(t.Age) CountFROM ( SELECT 0 FromNum, 10 ToNum, '0-10' Range UNION ALL SELECT 11, 20, '11-20' Range UNION ALL SELECT 21, 30, '21-30' Range UNION ALL SELECT 31, 40, '31-40' Range UNION ALL SELECT 41, 50, '41-50' ) zLEFT JOIN @test t on t.age between z.fromnum and z.tonumgroup by z.range
Peter LarssonHelsingborg, Sweden