Sql server查询选择实现for-each逻辑的数据

时间:2014-07-19 10:07:39

标签: sql sql-server tsql

我正在编写SQL查询来填充报表中的数据。我在这样的表格中有数据......

    Name           Gender           MainCategory            SubCategory

    Mark             M              Category 1              Sub Category 1
    Peter            M              Category 1              Sub Category 2
    Gemma            F              Category 1              Sub Category 1
    Paul             M              Category 3              Sub Category 2
    Mike             M              Category 3              Sub Category 4
    Elle             F              Category 3              Sub Category 4
...
...So on

我如何实现foreach逻辑..希望看到像......的结果。

   Description                                              Total

   Total Category 1 Employees of Sub Category 1               2
   Total Category 1 Employees of Sub Category 2               1
   Total Category 3 Employees of Sub Category 2               1
   Total Category 3 Employees of Sub Category 4               2

1 个答案:

答案 0 :(得分:0)

希望以下查询能为您提供帮助。

SELECT 'Total ' + MainCategory + ' Employees of ' + SubCategory As [Description],
       COUNT(*) As Total
FROM MyTable
Group BY MainCategory, SubCategory