我有一个看起来像这样的表:
CreatedDate TargetDate Value Name rowNum
2016-10-06 16:30:00.000 2016-10-16 00:00:00.000 17.97566 Joseph 1
2016-10-06 16:20:00.000 2016-10-16 00:00:00.000 1.176129 Heidi 1
2016-10-06 16:20:00.000 2016-10-15 23:00:00.000 1.196976 Heidi 1
2016-10-06 16:30:00.000 2016-10-15 23:00:00.000 15.15687 Joseph 1
2016-10-06 16:30:00.000 2016-10-15 22:00:00.000 11.04526 Joseph 1
2016-10-06 16:20:00.000 2016-10-15 22:00:00.000 1.539218 Heidi 1
我想把它转移到这样的表格中:
gen_dt_Joseph gen_dt_Heidi TargetDate JosephValue HeidiValue
2016-10-06 16:30:00.000 2016-10-06 16:20:00.000 2016-10-16 00:00:00.000 17.9757 1.1761
2016-10-06 16:30:00.000 2016-10-06 16:20:00.000 2016-10-15 23:00:00.000 15.1569 1.1970
2016-10-06 16:30:00.000 2016-10-06 16:20:00.000 2016-10-15 22:00:00.000 11.0453 1.5392
我的查询如下:
select CreatedDate as gen_dt_Joseph
,CreatedDate as gen_dt_Heidi
,TargetDate [TargetDate]
,[Joseph] [JosephValue]
,[Heidi] [HeidiValue]
FROM theTable
pivot (max(value) for Name in ( [Joseph],[Heidi])
) as pvt
order by TargetDate DESC
当然这是回归:
gen_dt_Joseph gen_dt_Heidi TargetDate JosephValue HeidiValue
2016-10-06 16:30:00.000 2016-10-06 16:30:00.000 2016-10-16 00:00:00.000 17.9757 NULL
2016-10-06 16:20:00.000 2016-10-06 16:20:00.000 2016-10-16 00:00:00.000 NULL 1.1761
2016-10-06 16:30:00.000 2016-10-06 16:30:00.000 2016-10-15 23:00:00.000 15.1569 NULL
2016-10-06 16:20:00.000 2016-10-06 16:20:00.000 2016-10-15 23:00:00.000 NULL 1.1970
2016-10-06 16:30:00.000 2016-10-06 16:30:00.000 2016-10-15 22:00:00.000 11.0453 NULL
2016-10-06 16:20:00.000 2016-10-06 16:20:00.000 2016-10-15 22:00:00.000 NULL 1.5392
所以基本上我想要一个记录包含每个TargetDate的两个值,但如果我有两个不同的CreatedDate,我想记录每个记录的最新记录。谁能帮我走最后一步呢?
答案 0 :(得分:1)
当必须转动多个列时,我更喜欢简单地使用CASE WHEN
语句和标准GROUP BY
子句。以下查询将为您提供所需的结果。
SELECT MAX(
CASE Name
WHEN 'Joseph' THEN CreatedDate
ELSE NULL
END
) AS gen_dt_Joseph
,MAX(
CASE Name
WHEN 'Heidi' THEN CreatedDate
ELSE NULL
END
) AS gen_dt_Heidi
,TargetDate
,MAX(
CASE Name
WHEN 'Joseph' THEN Value
ELSE NULL
END
) AS JosephValue
,MAX(
CASE Name
WHEN 'Heidi' THEN Value
ELSE NULL
END
) AS HeidiValue
FROM theTable
GROUP BY TargetDate
ORDER BY TargetDate DESC