2012-03-13 84 views
1

我稱之爲表work_type和數據的模樣:複式行轉換成列

Desc    L_type  Ch_ID  Mod_Date 
Std Process  11000  53901  2012-02-25 19:28:51.000 
Not Req   16000  53901  2012-02-26 20:44:47.000 
max sess   19000  53901  2012-02-25 19:44:05.000 
max sess regist 19000  53901  2012-02-25 19:46:05.000 

當L_TYPE有(以上數據爲防爆19000)多行則需要根據Mod_Date

最近的一次

我想輸出,如:

Te_pl  In_pl    Vn_pl   Ch_ID 
Not Req max sess regist  Std process 53901 

我寫這樣的查詢,但它不是我想要的:

Select Case when L_type = 11000 then Desc end as Vn_pl, 
Case when L_type = 16000 then Desc end as Te_pl, 
Case when L_type = 11000 then Desc end as In_pl, 
Ch_ID 
from dbo.Work_type 
+0

的可能重複的[合併多個結果在子查詢到單個逗號分隔值(http://stackoverflow.com/questions/111341/combine-multiple-results-in-a-subquery-into-a-單逗號分隔值) – danihp 2012-03-13 15:13:11

+0

@danihp我不認爲該請求是連接任何值加在一起。 – 2012-03-13 15:15:08

回答

2

如果你只指望需要三列那麼這應該做的伎倆 - 如果不是的話,我建議看動態旋轉代替:

;WITH data AS 
(
SELECT 
[desc] 
,l_type 
,ch_id 
,mod_date 
,DENSE_RANK() OVER (PARTITION BY ch_id,l_type ORDER BY mod_date DESC) AS row 
FROM dbo.Work_type 
) 
,data2 AS 
(
SELECT * 
,row_number() OVER (PARTITION BY ch_id ORDER BY mod_date DESC) AS row1 
from data 
WHERE row = 1 
) 
SELECT 
MAX(Case when row1 = 1 THEN [desc] END) AS te_pl 
,MAX(Case when row1 = 2 THEN [desc] END) AS in_pl 
,MAX(Case when row1 = 3 THEN [desc] END) AS vn_pl 
,CH_id 
FROM data2 
GROUP BY CH_ID 
+0

優秀這是我想要 – peter 2012-03-13 15:36:19

+0

好!你能幫助這個請http://stackoverflow.com/questions/9687622/sql-server-exporting-data-from-a-view – 2012-03-13 16:41:58

0

這裏是轉整個表的基於XML的方法:here

0

你是不是想透視數據?

退房的PIVOT關鍵字。