SQL 行到列

SQL rows to column

这是我的查询。

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

知道如何编写查询来获得这个结果吗?

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

这称为旋转,更多示例请看这里 SQL Server: Examples of PIVOTing String data

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