我想将SQL表转换为以下格式。有人可以告诉我这怎么可能吗?我是这个主题的新手,所以我对此并不了解。我已经尝试过使用SSIS的数据透视功能,但是我无法使用。
有人可以告诉我一个SQL语句或SSIS作业来帮助我解决此问题吗?
答案 0 :(得分:0)
答案 1 :(得分:0)
不确定是否要从红色开始然后变为绿色或相反。
无论哪种方式,您都需要PIVOT and UNPIVOT函数。
让我们创建一些测试表来模拟您的数据
create table #_base
(
Dt_ref datetime
, Val float
)
insert into #_base
values
('2018-12-16 01:00:00.000', 36.96)
,('2018-12-16 02:00:00.000', 38.81)
,('2018-12-16 03:00:00.000', 38.1)
,('2018-12-16 04:00:00.000', 38.58)
,('2018-12-16 05:00:00.000', 38.23)
,('2018-12-16 06:00:00.000', 38.42)
,('2018-12-17 01:00:00.000', 96.96)
,('2018-12-17 02:00:00.000', 98.81)
,('2018-12-17 03:00:00.000', 98.1)
,('2018-12-17 04:00:00.000', 98.58)
,('2018-12-17 05:00:00.000', 98.23)
,('2018-12-17 06:00:00.000', 98.42)
select * from #_base
让我们创建您的绿色数据集
select cast(Dt_ref as date) as Day
, datepart (hour,Dt_ref) as Hour
, Val
into #_base_green
from #_base
select * from #_base_green
如果要从绿色变为红色,只需PIVOT
select Day
, [1] as Hour1
, [2] as Hour2
, [3] as Hour3
, [4] as Hour4
, [5] as Hour5
, [6] as Hour6
into #_result_red
from #_base_green p
pivot (
sum(val)
for Hour in
( [1]
, [2]
, [3]
, [4]
, [5]
, [6] )
) as pvt
select * from #_result_red
从红色到绿色,UNPIVOT
select *
into #_base_red
from #_result_red
select * from #_base_red
select
dateadd(hh, cast(substring(hours,5,6) as int), cast(day as datetime))
, value
into #_result_green
from
(
select Day, Hour1
,Hour2
,Hour3
,Hour4
,Hour5
,Hour6
from #_base_red
) p
unpivot (value for Hours in (Hour1
,Hour2
,Hour3
,Hour4
,Hour5
,Hour6)
) as unpvt
select * from #_result_green