sql将某些列透视到行中

eoigrqb6  于 2021-08-13  发布在  Java
关注(0)|答案(4)|浏览(357)

这是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函数得到这个结果?

ulmd4ohb

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

vd2z7a6w

vd2z7a6w2#

你可以通过交叉申请取消你的价值观

Select B.*
      ,A.Department
      ,A.Date
 From  YourTable A
 Cross Apply ( values ('Income'  ,Income  )
                     ,('Expences',Expenses)
                     ,('Other'   ,Other   )
             ) B(Description,Value)
mzsu5hc0

mzsu5hc03#

你可以用 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);
vs91vp4v

vs91vp4v4#

只是为了好玩,这里有一个小技巧,可以“动态”取消激活数据,而无需动态sql或声明所有列。
例子

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

退货

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

相关问题