我尝试编写一个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
答案 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;