简体   繁体   English

SQL Server:2个Pivot问题

[英]SQL Server : 2 Pivot Questions

All the pivot examples i saw till now use aggregate functions. 到目前为止我看到的所有枢轴示例都使用聚合函数。 So i have no idea how i can achieve the following: 所以我不知道如何实现以下目标:

I have this simple table for test purposes: 我有这个简单的表用于测试目的:

;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))

I want to achieve the following: 我想实现以下目标:

  1. To rotate the table like this: 要像这样旋转表:

    在此输入图像描述

  2. And I want to rotate the following query: 我想旋转以下查询:

     SELECT city, COUNT(city) AS num_of_customers FROM CUSTOMERS GROUP BY city; 

which produces the following result: 产生以下结果:

在此输入图像描述

I want to display it like this: 我想像这样显示它:

在此输入图像描述

I never worked with pivot tables until now and I would be grateful for any kind of help. 到目前为止我从未使用过数据透视表,我会感激任何帮助。

PS: table name is Customers . PS:表名是Customers

Both queries are easy to do in a dynamic fashion, which is nice if you don't have a fixed number of rows and need the query to adapt to the number of rows. 这两个查询都很容易以动态方式进行,如果您没有固定数量的行并且需要查询以适应行数,那么这很好。

The first query: 第一个查询:

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)

Result: 结果:

1       2       3       4       5       6       7           8
Messi   Ronaldo Weah    Nedved  Hagi    Puskas  Stoichkov   Di Baggio

The second query: 第二个查询:

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)

Result: 结果:

Dubai       Graz        Istanbul    Wien
----------- ----------- ----------- -----------
2           2           1           3

Second query can be achieved like below 第二个查询可以像下面这样实现

select Dubai,Graz,Istanbul,Wien
from Customers
pivot
(
COUNT(city)
for city
in ([Dubai],[Graz],[Istanbul],[Wien])
)
as pivottab

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM