2014-10-09 89 views
0

我有如下表:水平到垂直查看SQL

oDate  value1  value2  value3  value4 
2014-06-01 10   20   30   40 
2014-06-02 20   25   35   50 

我想有以下結果

oDate  oField  oValue 
2014-06-01 Value1  10 
2014-06-01 Value2  20 
2014-06-01 Value3  30 
2014-06-01 Value4  40 

是否可以做,在SQL?
需要建議。乾杯,

+0

[使用PIVOT和UNPIVOT](http://technet.microsoft.com/en-us/library/ms177410(V = SQL.105)的.aspx) – Pred 2014-10-09 06:56:03

回答

1

你可以這樣做:

測試數據:

DECLARE @tbl TABLE(oDate DATETIME,value1 INT,value2 INT,value3 INT,value4 INT) 
INSERT INTO @tbl 
VALUES 
('2014-06-01',10,20,30,40), 
('2014-06-02',20,25,35,50) 

UNPIVOT查詢

SELECT 
    * 
FROM 
(
    SELECT 
     oDate, 
     value1, 
     value2, 
     value3, 
     value4 
    FROM 
     @tbl 
) sourceTable 
UNPIVOT 
(
    oField FOR oValue IN 
    (value1,value2,value3,value4) 
) AS unpvt 

參考:

0

這個怎麼樣?

select 
    oDate, 
    'Value1' as oField, 
    value1 as oValue 
from yourTable 
union all 
select 
    oDate, 
    'Value2' as oField, 
    value2 as oValue 
from yourTable 
union all 
select 
    oDate, 
    'Value3' as oField, 
    value3 as oValue 
from yourTable 
union all 
select 
    oDate, 
    'Value4' as oField, 
    value4 as oValue 
from yourTable 
order by oDate, oField 
1

嘗試此

SELECT DISTINCT ODATE,VALUE,FIELD 
FROM 
    (SELECT odate,value1,value2,value3,value4 
    FROM #temp) p 
UNPIVOT 
    (VALUE FOR FIELD IN 
     (value1,value2,value3,value4) 
)AS unpvt; 
GO