SQL Server查询在今天的日期返回1行与多列计数

时间:2017-06-06 21:37:10

标签: sql-server

我尝试编写一个SQL Server查询,其中1行作为客户的多个Region区域的日期戳。它为每个case语句返回一行。

Customer    Region
1           A
2           A
3           B
4           B
5           B

SELECT 
CONVERT(VARCHAR(10), GETDATE(), 111),
case when Region = 'A' then COUNT(Customer) end as 'Region A',
case when Region = 'B' then COUNT(Customer) end as 'Region B',
FROM tbl_Customers

结果:

Date        Region A    Region B
2017/06/07  2           NULL
2017/06/07  NULL        3

1 个答案:

答案 0 :(得分:1)

您只需要在聚合函数中添加CASE表达式:

SELECT  CONVERT(VARCHAR(10), GETDATE(),111) [Date],
        COUNT(CASE WHEN Region = 'A' THEN Customer END) [Region A],
        COUNT(CASE WHEN Region = 'B' THEN Customer END) [Region B]
FROM tbl_Customers;