我有一个名为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有多行时(对于上述数据中的Ex 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 :(得分: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
答案 1 :(得分:0)
以下是一种基于XML的转换整个表的方法:here
答案 2 :(得分:0)
您是否尝试透视数据?
查看PIVOT关键字。