我有下表:
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 :(得分: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
参考:
答案 1 :(得分: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
答案 2 :(得分: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