如何基于行数据动态地枢轴列

时间:2019-05-10 03:31:40

标签: sql sql-server pivot

我正在尝试使用数据透视表将行数据列出为一列。但是,当我到处搜索时,大多数人都使用静态数据透视表,它会自行列出所需的列。

但是在我的情况下,我希望该列从行数据中动态列出。

-----------------------------------------
 Date      Ingredients       TotalAmount
-----------------------------------------
1/2/19        butter            20.00
1/2/19        butter             5.00
2/3/19        Flour              7.00
2/3/19        Flour              3.00
4/3/19        Butter             4.00
2/4/19        Salt              12.00
3/4/19        Cinnamon           2.00
5/4/19        Cinnamon          13.00
.
.
.
.
.
.
.
.
Many more to comes
-----------------------------------------

我已经在Google上进行了如下尝试,尝试了动态枢轴;但是,它没有找到任何解决方案。

DECLARE @s AS NVARCHAR(MAX)

SELECT @s= ISNULL(@s + ',','') 
       + QUOTENAME(Ingredients)
FROM (SELECT Ingredients from Sales) AS Y

SELECT * FROM (
SELECT  S.Date, S.TotalAmount, A.Ingredients FROM Sales S
) Z
PIVOT ( SUM(TotalAmount) FOR Ingredients IN (' + @s +')) AS MENU

结果:

Msg 102, Level 15, State 1, Line 23
Incorrect syntax near ' + @PLUNAME +'.

我希望查询结果如下:

-----------------------------------------------------------------
 Date      Butter    Flour    Salt    Cinnamon   ...  ...  ... and many more     
-----------------------------------------------------------------
1/2/19     25.00    
2/3/19              10.00
4/3/19      4.00
2/4/19                       12.00
3/4/19                                 2.00
5/4/19                                13.00
.
.
.
.

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

CREATE TABLE List(Date date, ingredients varchar(100), TotalAmount FLOAT);

INSERT INTO List VALUES 
('01/02/2019','butter',20.00),
('01/02/2019','butter',5.00),
('02/03/2019','Flour',7.00),
('02/03/2019','Flour',3.00),
('04/03/2019','butter', 4.00),
('02/04/2019','Salt',12.00),
('03/04/2019','Cinnamon',2.00),
('05/04/2019','Cinnamon',13.00);


DECLARE @columns NVARCHAR(MAX);

SELECT @columns = STUFF((
            SELECT DISTINCT ',' + '['+ingredients+']' FROM List
            FOR XML PATH('')
            ), 1, 1, '')
FROM List;


SET @sql = 'SELECT Date,' + @columns + ' FROM
(
  SELECT Date, ingredients, TotalAmount FROM List
) AS src
PIVOT
(
  SUM(src.TotalAmount) FOR src.ingredients IN ('+ @columns
  + ')
) AS p;';

EXEC sp_executesql @sql;