这是我的疑问。
select name, walk_to, count(*) count
from walk
where name='Rizwan'
group by name, walk_t0;
这会产生如下数据:
NAME WALK_TO COUNT
Rizwan Cafe 2
Rizwan Arena 10
Rizwan Outside 20
还有其他用户的数据。我想要的是:
NAME CAFE ARENA OUTSIDE
Rizwan 2 10 20
John 3 21 90
James 5 5 9
知道如何编写查询来获得此结果吗?
答案 0 :(得分:0)
SELECT name,
SUM(CASE WHEN walk_to = 'Cafe' THEN 1 ELSE 0 END) Cafe,
SUM(CASE WHEN walk_to = 'Arena' THEN 1 ELSE 0 END) Arena,
SUM(CASE WHEN walk_to = 'Outside' THEN 1 ELSE 0 END) Outside
FROM walk
GROUP BY name
这个被称为pivioting,更多示例请看SQL Server: Examples of PIVOTing String data
答案 1 :(得分:0)
select name,
sum(case when walk_to='Cafe' then 1 else 0 end) as CAFE,
sum(case when walk_to='Arena' then 1 else 0 end) as ARENA,
sum(case when walk_to='Outside' then 1 else 0 end) as OUTSIDE
FROM walk
GROUP BY name