我到目前为止看到的所有数据透视示例都使用聚合函数。所以我不知道如何实现以下目标:
我有这个简单的表用于测试目的:
;WITH cte AS (
SELECT * FROM (VALUES
(1, 'Messi', 'Graz'),
(2, 'Ronaldo', 'Graz'),
(3, 'Weah', 'Wien'),
(4, 'Nedved', 'Wien'),
(5, 'Hagi', 'Wien'),
(6, 'Puskas', 'Istanbul'),
(7, 'Stoichkov', 'Dubai'),
(8, 'Di Baggio', 'Dubai')
) as t(cid, name, city))
我想实现以下目标:
要像这样旋转表格:
我想轮换以下查询:
SELECT city, COUNT(city) AS num_of_customers
FROM CUSTOMERS
GROUP BY city;
产生以下结果:
我想这样显示:
到目前为止,我从未使用数据透视表,我将不胜感激任何帮助。
PS:表格名称为Customers
。
答案 0 :(得分:2)
这两个查询都很容易以动态方式进行,如果你没有固定数量的行并且需要查询来适应行数,这很好。
第一个查询:
DECLARE @players AS VARCHAR(MAX)
SELECT @players = STUFF((SELECT DISTINCT ',['+CAST(cid AS VARCHAR(10))+']'
FROM customers FOR XML PATH('')),1,1,'')
DECLARE @dynamic_pivot_query AS VARCHAR(MAX)
SET @dynamic_pivot_query = 'SELECT '+@players+'
FROM (SELECT cid, name FROM customers) AS S
PIVOT (MAX(name) FOR cid IN ('+@players+')
) AS P'
EXEC(@dynamic_pivot_query)
结果:
1 2 3 4 5 6 7 8
Messi Ronaldo Weah Nedved Hagi Puskas Stoichkov Di Baggio
第二个问题:
DECLARE @cities AS VARCHAR(MAX)
SELECT @cities = STUFF((SELECT DISTINCT ',['+city+']'
FROM customers FOR XML PATH('')),1,1,'')
DECLARE @dynamic_pivot_query AS VARCHAR(MAX)
SET @dynamic_pivot_query = 'SELECT '+@cities+'
FROM (SELECT city FROM customers) as S
PIVOT (COUNT(city) FOR city IN ('+@cities+')
) AS P'
EXEC(@dynamic_pivot_query)
结果:
Dubai Graz Istanbul Wien
----------- ----------- ----------- -----------
2 2 1 3
答案 1 :(得分:1)
可以实现第二次查询,如下所示
select Dubai,Graz,Istanbul,Wien
from Customers
pivot
(
COUNT(city)
for city
in ([Dubai],[Graz],[Istanbul],[Wien])
)
as pivottab