[英]How do you pivot some columns into rows using sql or t-sql
Here is the table这是桌子
Income|Expenses|Other|Department|Date
2k | 4k| .5k|Marketing |2014-05-28
52k | 7k| .1k|Sales |2014-04-01
Result结果
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
Actually, I can use SELECT + UNION to get the result but the requirement is to use Pivot.实际上,我可以使用 SELECT + UNION 来获得结果,但要求是使用 Pivot。
How to get this result using PIVOT function?如何使用 PIVOT function 获得此结果?
You can unpivot your values via a Cross Apply您可以通过交叉应用取消您的价值观
Select B.*
,A.Department
,A.Date
From YourTable A
Cross Apply ( values ('Income' ,Income )
,('Expences',Expenses)
,('Other' ,Other )
) B(Description,Value)
You can use apply
:您可以使用
apply
:
select tt.Description, tt.Value, t.Department, t.Date
from table t cross apply
( values ('Income', Income), ('Expenses', Expenses), ('Other', Other)
) tt(Description, Value);
you can use UNPIVOT
你可以使用
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
Result:结果:
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
Just for fun , here is a little technique to "dynamically" unpivot your data without Dynamic SQL or declaring all the columns.只是为了好玩,这里有一个小技巧,可以在没有动态 SQL 或声明所有列的情况下“动态”取消数据透视。
Example例子
Select Description = B.[Key]
,B.Value
,A.Department
,A.Date
From YourTable A
Cross Apply ( Select [Key]
,Value
From OpenJson( ( Select A.* for JSON Path,Without_Array_Wrapper) )
Where [Key] not in ('Department','Date')
) B
Returns退货
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.