这是table
Income|Expenses|Other|Department|Date
2k | 4k| .5k|Marketing |2014-05-28
52k | 7k| .1k|Sales |2014-04-01
结果
Description|Value|Department|Date
Income | 2k|Marketing |2014-05-28
Expenses | 4k|Marketing |2014-05-28
Other | .5k|Marketing |2014-05-28
Income | 52k|Sales |2014-04-01
Expenses | 7k|Sales |2014-04-01
Other | .1k|Sales |2014-04-01
实际上,我可以使用select+union来获得结果,但需要使用pivot。
如何使用pivot函数得到这个结果?
4条答案
按热度按时间ulmd4ohb1#
你可以用
UNPIVOT
```DECLARE @SampleData TABLE (Income VARCHAR(20), Expenses VARCHAR(20), Other VARCHAR(20), Department VARCHAR(20), Date [Date])
INSERT INTO @SampleData VALUES
('2k ', '4k','.5k','Marketing','2014-05-28'),
('52k', '7k','.1k','Sales ','2014-04-01')
SELECT Description, Value, Department, Date
FROM @SampleData T
UNPIVOT ([Value] FOR [Description] IN ([Income], [Expenses], [Other])) AS UNPVT
Description Value Department Date
Income 2k Marketing 2014-05-28
Expenses 4k Marketing 2014-05-28
Other .5k Marketing 2014-05-28
Income 52k Sales 2014-04-01
Expenses 7k Sales 2014-04-01
Other .1k Sales 2014-04-01
vd2z7a6w2#
你可以通过交叉申请取消你的价值观
mzsu5hc03#
你可以用
apply
:vs91vp4v4#
只是为了好玩,这里有一个小技巧,可以“动态”取消激活数据,而无需动态sql或声明所有列。
例子
退货