我有一个包含许多ID的表,其中包含两个可能的“类型”,并且每个ID与“类型”相关联的日期很多。我想选择ID,“Type”A的最新日期和“Type”B的最接近日期,大于A类。
Sample Table
ID Type Date
1 A 1/5/2013
1 A 1/10/2013
1 B 1/1/2013
2 A 2/10/2013
2 A 2/9/2013
2 B 2/15/2013
2 B 2/20/2013
3 A 3/15/2013
3 B 3/10/2013
3 B 3/20/2013
期望的结果
ID Date A Date B
2 2/10/2013 2/15/2013
3 3/15/2013 3/20/2013
ID 1保持关闭,因为它不满足条件B>最大(typeA){1/10/13} ID 2等于max(typeA){2/10/13 vs 2/9/13},而Date B {2/15/13}大于Date A,并且是满足该条件的两个日期中最接近的日期。 ID 3仅等于大于日期A的条目和最接近的B条目{3/20/13}
我已经尝试了几次min,max和row / partition迭代,但结果已经停止了几个符合条件的条目。使用Sql Server 2008 V 10.非常感谢任何帮助
答案 0 :(得分:4)
假设SQL Server 2005+,您可以使用:
;WITH CTE AS
(
SELECT [ID],
[Type],
[Date],
RN = ROW_NUMBER() OVER(PARTITION BY [ID] ORDER BY [Date] DESC)
FROM YourTable
WHERE [Type] = 'A'
)
SELECT A.[ID],
A.[Date] [Date A],
B.[Date] [Date B]
FROM (SELECT *
FROM CTE
WHERE RN = 1) A
CROSS APPLY (SELECT TOP 1 [Date]
FROM YourTable
WHERE [Type] = 'B'
AND [ID] = A.[ID]
AND [Date] > A.[Date]
ORDER BY [Date]) B
结果是:
╔════╦═════════════════════════════════╦═════════════════════════════════╗
║ ID ║ DATE A ║ DATE B ║
╠════╬═════════════════════════════════╬═════════════════════════════════╣
║ 2 ║ February, 10 2013 00:00:00+0000 ║ February, 15 2013 00:00:00+0000 ║
║ 3 ║ March, 15 2013 00:00:00+0000 ║ March, 20 2013 00:00:00+0000 ║
╚════╩═════════════════════════════════╩═════════════════════════════════╝
here is你可以试试。{/ p>
答案 1 :(得分:0)
您可以使用:
SELECT ID, A_Date, B_Date
FROM (
SELECT a.ID,a.Date 'A_Date', b.Date 'B_Date', ROW_NUMBER() OVER (PARTITION BY a.ID ORDER BY DATEDIFF(day,a.Date,b.Date))'RowRank'
FROM (SELECT ID,Type, MAX(Date)'Date'
FROM Table1
WHERE Type = 'A'
GROUP BY ID,Type
)a
JOIN Table1 b
ON a.ID = b.ID
AND a.Type <> b.Type
AND a.Date < b.Date
)sub
WHERE RowRank = 1
演示:SQL Fiddle