垂直到水平视图SQL

时间:2014-10-01 06:50:43

标签: sql sql-server sql-server-2008

我有下表:

ID    GroupCode     oDate        oTime      oValue
1     A             2014-06-01   00:00:00   200
2     A             2014-06-01   01:00:00   300
3     A             2014-06-01   02:00:00   400
FF. until oTime reach 23:00:00 then it will create a new date. which is 2014-06-02
25    B             2014-06-01   00:00:00   600
26    B             2014-06-01   01:00:00   700
27    B             2014-06-01   02:00:00   725
FF. until oTime reach 23:00:00 then it will create a new date. which is 2014-06-02

我的问题是,如何在SQL View上水平进行?我希望得到以下结果:

GroupCode1   oDate1       oTime1      oValue1      GroupCode2      oDate2      oTime2    oValue2
A            2014-06-01   00:00:00    200          B               2014-06-01  00:00:00  600
A            2014-06-01   01:00:00    300          B               2014-06-01  01:00:00  700
A            2014-06-01   02:00:00    400          B               2014-06-01  02:00:00  725

有谁知道怎么做?
谢谢。真的很感激。

1 个答案:

答案 0 :(得分:1)

如果只有3个组代码ABC,并且每个组代码对于给定日期有23行,那么您可以写为:

select GroupCode1, oDate1,oTime1,oValue1,GroupCode2, oDate2,oTime2,oValue2
       ,GroupCode3, oDate3,oTime3,oValue3
from 
(select GroupCode as GroupCode1,
       oDate as oDate1,
       oTime as oTime1,
       oValue as oValue1
from table1 
where GroupCode = 'A')T1 full join
(select GroupCode as GroupCode2,
       oDate as oDate2,
       oTime as oTime2,
       oValue as oValue2
from table1 
where GroupCode = 'B')T2 on T1.oDate1 = T2.oDate2 and T1.oTime1 = T2.oTime2
full join 
(select GroupCode as GroupCode3,
       oDate as oDate3,
       oTime as oTime3,
       oValue as oValue3
from table1 
where GroupCode = 'C')T3 on T1.oDate1 = T3.oDate3 and T1.oTime1 = T3.oTime3

Demo