我读过关于MS数据透视表的东西,我仍然有问题得到这个正确的。

我有一个正在创建的临时表,我们会说第1列是一个商店号,第2列是一个星期号,最后第3列是某种类型的总数。此外,周数是动态的,商店数是静态的。

Store      Week     xCount
-------    ----     ------
102        1        96
101        1        138
105        1        37
109        1        59
101        2        282
102        2        212
105        2        78
109        2        97
105        3        60
102        3        123
101        3        220
109        3        87

我希望它是一个数据透视表,像这样:

Store        1          2          3        4        5        6....
----- 
101        138        282        220
102         96        212        123
105         37        
109

店铺编号写在边上,星期写在上面。


当前回答

select * from (select name, ID from Empoyee) Visits
    pivot(sum(ID) for name
    in ([Emp1],
    [Emp2],
    [Emp3]
    ) ) as pivottable;

其他回答

这是动态的# of weeks。

完整示例:SQL动态Pivot

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') + QUOTENAME(Week)
FROM (SELECT DISTINCT Week FROM #StoreSales) AS Weeks

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT Store, ' + @ColumnName + ' 
    FROM #StoreSales
    PIVOT(SUM(xCount) 
          FOR Week IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

Pivot是SQL操作符之一,用于将输出中的唯一数据从一列转换为多列。这也意味着将行转换为列(旋转表)。让我们考虑这张桌子,

如果我想根据每个客户的产品类型(扬声器、眼镜、耳机)过滤这些数据,那么使用Pivot操作符。

Select CustmerName, Speaker, Glass, Headset  
from TblCustomer  
   Pivot  
    (  
     Sum(Price) for Product in ([Speaker],[Glass],[Headset])  
    ) as PivotTable 

你可以这样做:

SELECT * 
FROM yourTable
PIVOT (MAX(xCount) 
       FOR Week in ([1],[2],[3],[4],[5],[6],[7])) AS pvt

DEMO

select * from (select name, ID from Empoyee) Visits
    pivot(sum(ID) for name
    in ([Emp1],
    [Emp2],
    [Emp3]
    ) ) as pivottable;

只是给你一些其他数据库如何解决这个问题的想法。DolphinDB还内置了对旋转的支持,sql看起来更加直观和整洁。它非常简单,只需指定键列(Store)、旋转列(Week)和计算的度量(sum(xCount))。

//prepare a 10-million-row table
n=10000000
t=table(rand(100, n) + 1 as Store, rand(54, n) + 1 as Week, rand(100, n) + 1 as xCount)

//use pivot clause to generate a pivoted table pivot_t
pivot_t = select sum(xCount) from t pivot by Store, Week

DolphinDB是一个柱状的高性能数据库。演示中的计算成本在戴尔xps笔记本电脑(i7 cpu)上低至546毫秒。欲了解更多详细信息,请参阅DolphinDB在线手册https://www.dolphindb.com/help/index.html?pivotby.html