ID Date1 T1 Date2 T2 Date3 T3 Date4 T4
1 DT11 Y ----------NULL-----------------------
2 DT11 N DT22 Y ----------NULL----------
3 DT31 N DT32 Y DT33 Y --NULL-----
4 ----NULL--- DT42 Y ---NULL--- DT44 Y
5 DT51 Y ---NULL-- DT53 Y --NULL-----
我有一个具有上述结构的表 Table1。
要求:
- 检查 (T1 - T5) 中哪一个有“Y”
- 如果有多个“Y”,则比较日期以获取最近的日期
- 在具有最近日期的日期字段的名称或部分名称的新字段中设置一个值。
所以,o/p 应该是
ID Most-recent-Date-Flag
---------------------------------------------------
1 "Date1 or T1" -> Since all others are null
2 "Date2 or T2" -> T2 has 'Y'
3 "Date3 or T3" -> one 'N' and multiple 'Y', DT33 is most recent
4 "Date4 or T4" -> multiple 'Y', DT44 is most recent
5 "Date5 or T5" -> multiple 'Y', DT53 is most recent
我已经设法创建查询来比较日期。如下:
SELECT [ID]
, MAX(UNPIVOT_DATE) AS MOST_RECENT_DATE
FROM
(
SELECT
[ID]
,[Date1]
,[Date2]
,[Date3]
,[Date4]
FROM TABLE1
)SRC_TABLE
UNPIVOT
(
UNPIVOT_DATE
FOR DATES IN
(
[Date1]
,[Date2]
,[Date3]
,[Date4]
)
)UNPIVOT_TABLE
GROUP BY [ID]
我被困在检查(T1-T4)字段中的“Y”并在比较后获取最近日期的列名的地方。
希望这个解释有帮助!
08/04/2013
非常感谢@MarcinJuraszek。有用!!无论如何我也可以传递字段的列名(T1-T4)吗?我尝试了以下方法,但没有奏效。
SELECT t.[ID]
,MAX(t.Date) as MOST_RECENT_DATE
--,t.Column_Name
FROM
(
SELECT [ID]
,[Date1] as Date
,[T1] as T
-- ,COL_NAME(OBJECT_ID('Table1'), 2) AS Column_Name
FROM Table1
UNION ALL
SELECT [ID]
,[Date2] as Date
,[T2] as T
-- ,COL_NAME(OBJECT_ID('Table1'), 4) AS Column_Name
FROM Table1
UNION ALL
SELECT [ID]
,[Date3] as Date
,[T3] as T
-- ,COL_NAME(OBJECT_ID('Table1'), 6) AS Column_Name
FROM Table1
UNION ALL
SELECT [ID]
,[Date4] as Date
,[T4] as T
-- ,COL_NAME(OBJECT_ID('Table1'), 8) AS Column_Name
FROM Table1
) t
WHERE t.T = 'Y'
GROUP BY t.[ID]
--, t.Column_Name
ORDER by [ID]