我有一张表格如下
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
答案 0 :(得分: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
更新:您在这里寻找的是如何pivot您的列,但您的查询问题是没有聚合列,您可以聚合其他列,当您GROUP BY column_date
。由于您需要GROUP BY column_date
,因此其他列需要位于GROUP BY clause
中或包含在聚合函数中。因此,我使用聚合函数MAX
作为解决方法。如果你知道想要正确转动的值,这很好。但是,如果要转动未知或更改数量的值,则需要动态执行此操作。尝试在SQL Server中搜索动态数据透视,您会发现使用动态SQL的许多变通方法。例如,请参阅以下两篇文章: