2

我有一张如下表

column_date | color | qty | supplier | location
1 June 2012 | red   | 2   | XY       | A wing
1 June 2012 | red   | 1   | AB       | A wing
1 June 2012 | blue  | 4   | CD       | A wing
1 June 2012 | blue  | 1   | XY       | B wing
2 June 2012 | yellow| 13  | CD       | B wing
2 June 2012 | green | 45  | CD       | A wing
2 June 2012 | blue  | 32  | AB       | A wing
2 June 2012 | red   | 37  | XY       | A wing
2 June 2012 | red   | 2   | XY       | B wing
2 June 2012 | red   | 1   | AB       | A wing
2 June 2012 | blue  | 4   | CD       | A wing
3 June 2012 | red   | 1   | AB       | B wing
3 June 2012 | blue  | 4   | CD       | A wing
3 June 2012 | blue  | 1   | XY       | B wing
3 June 2012 | yellow| 13  | CD       | B wing
3 June 2012 | green | 45  | CD       | A wing
3 June 2012 | blue  | 32  | AB       | A wing

我想有一个像下面这样的输出。我不确定在查询中是否可能,如果可能的话,我不知道如何开始。我正在寻找您的建议或可能的查询来显示这样的输出。谢谢你。

                                    Supplier
Date           |        XY         |        CD          |       AB
               | A wing  | B wing  | A wing  | B wing   | A wing  | B wing
1 June 2012    |  2      |  1      |  4      | 0        | 1       | 0
2 June 2012    | 37      |  2      |  49     | 13       | 33      | 0
3 June 2012    | 0       |  1      |  49     | 13       | 32      | 1
Total          | 39      |  4      | 102     | 26       | 66      | 1
4

1 回答 1

0
SELECT column_date,
    MAX(CASE WHEN supplier = 'XY' AND location = 'A wing' THEN qty END) AS 'XY A wing',
    MAX(CASE WHEN supplier = 'XY' AND location = 'B wing' THEN qty END) AS 'XY B wing',
    MAX(CASE WHEN supplier = 'CD' AND location = 'A wing' THEN qty END) AS 'CD A wing',
    MAX(CASE WHEN supplier = 'CD' AND location = 'B wing' THEN qty END) AS 'CD B wing',
    MAX(CASE WHEN supplier = 'AB' AND location = 'A wing' THEN qty END) AS 'AB A wing',
    MAX(CASE WHEN supplier = 'AB' AND location = 'B wing' THEN qty END) AS 'AB B wing'
FROM @t
GROUP BY column_date

演示

更新:您在这里寻找的是如何旋转您的列,但您的查询的问题是没有聚合列可以聚合其他列GROUP BY column_date。既然您需要GROUP BY column_date,那么其他列需要在聚合函数中GROUP BY clause或包含在聚合函数中。因此,我使用聚合函数MAX作为解决方法。如果您知道要正手旋转的值,这很好。但是,如果您想旋转未知或更改数量的值,那么您需要动态地执行此操作。尝试在 SQL Server 中搜索Dynamic Pivoting,您会发现很多使用动态 SQL 的解决方法。例如看这两篇文章:

于 2012-07-11T15:20:15.477 回答