2009-02-13 75 views
0

我有一個SQL查詢(使用MS-SQL 2005),其產生與這些列中的數據:如何UNPIVOT將列拆分成行?

TimeStamp | Speed | Height 
--------------------------- 
10  | 50 | 300   <-- one row for the max values 
10  | 10 | 70   <-- a second row for the min values 

鑑於第一:

TimeStamp | SpeedMax | SpeedMin | HeightMax | HeightMin 
------------------------------------------------------- 
10  | 50  | 10  | 300  | 70 

的形式,我需要它雖然是這個結果集...我需要什麼查詢才能將數據轉換爲第二種格式?我認爲這可能涉及到一個不透明的問題,但我對此並不熟悉,並且在編寫什麼時遇到問題。

非常感謝。

回答

2
SELECT TimeStamp, 
     minmax, 
     CASE WHEN minmax = 0 THEN SpeedMax ELSE SpeedMin END AS Speed 
     CASE WHEN minmax = 0 THEN HeightMax ELSE HeightMin END AS Height 
FROM Table, 
(
    SELECT 0 AS minmax 
    UNION ALL 
    SELECT 1 
) mm 

您可以添加

OPTION (FORCE ORDER) 

避免Table

1

雙掃描嘗試

SELECT TimeStamp, SpeedMax AS Speed, HeightMax AS Height 
FROM Table 
UNION ALL 
SELECT TimeStamp, SpeedMin AS Speed, HeightMin AS Height 
FROM Table