SQL:使用CASE并仅返回最大值

时间:2013-09-04 19:41:18

标签: sql case where

对此问题中的任何新手遗漏或晦涩事件进行先发制人的道歉。

我想在约会时加入两张桌子。

Table1:
Closing Date
2013-04-26 00:00:00.000
2013-01-26 00:00:00.000

Table2:
Price Date
2013-04-24 00:00:00.000
2013-04-25 00:00:00.000
2013-04-26 00:00:00.000
2013-01-22 00:00:00.000
2013-01-23 00:00:00.000
2013-01-24 00:00:00.000

我想从Table2中为Table1中的每个日期提取最接近的日期(在前5天内),然后将其指定为“MATCH”或“NONMATCH”。

我有以下代码

CASE Table2.PricingDate 
    WHEN Table1.[ClosingDate] THEN 'MATCH'
    WHEN DATEADD(D,-1, Table1.[ClosingDate]) THEN 'NONMATCH'
    WHEN DATEADD(D,-2, Table1.[ClosingDate]) THEN 'NONMATCH'
    WHEN DATEADD(D,-3, Table1.[ClosingDate]) THEN 'NONMATCH'
    WHEN DATEADD(D,-4, Table1.[ClosingDate]) THEN 'NONMATCH'
    WHEN DATEADD(D,-5, Table1.[ClosingDate]) THEN 'NONMATCH'
END [Match]

FROM Table2 INNER JOIN Table1
    ON Table2.PricingDate 
           BETWEEN DATEADD(D,-5,Table1.[ClosingDate]) AND Table1.[ClosingDate]

    WHERE
    CASE Table2.PricingDate 
        WHEN Table1.[ClosingDate] THEN 'MATCH'
        WHEN DATEADD(D,-1, Table1.[ClosingDate]) THEN 'NONMATCH'
        WHEN DATEADD(D,-2, Table1.[ClosingDate]) THEN 'NONMATCH'
        WHEN DATEADD(D,-3, Table1.[ClosingDate]) THEN 'NONMATCH'
        WHEN DATEADD(D,-4, Table1.[ClosingDate]) THEN 'NONMATCH'
        WHEN DATEADD(D,-5, Table1.[ClosingDate]) THEN 'NONMATCH'
    END  IS NOT NULL

问题是这会为每个ClosingDate返回多个PricingDate:

**Closing Date            Price Date                Match**
2013-04-26 00:00:00.000   2013-04-24 00:00:00.000   NONMATCH
2013-04-26 00:00:00.000   2013-04-25 00:00:00.000   NONMATCH
2013-04-26 00:00:00.000   2013-04-26 00:00:00.000   MATCH
2013-01-26 00:00:00.000   2013-01-22 00:00:00.000   NONMATCH
2013-01-26 00:00:00.000   2013-01-23 00:00:00.000   NONMATCH
2013-01-26 00:00:00.000   2013-01-24 00:00:00.000   NONMATCH

我希望它只返回:

**Closing Date            Price Date                Match**
2013-04-26 00:00:00.000   2013-04-26 00:00:00.000   MATCH
2013-01-26 00:00:00.000   2013-01-24 00:00:00.000   NONMATCH

我怎样才能让每个closingDate只返回一个pricingDate? 非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

假设您正在使用SQL Server:

select
    T1.[Closing Date], T2.[Price Date],
    case
        when T1.[Closing Date] = T2.[Price Date] then 'MATCH'
        else 'NONMATCH'
    end as [Match]
from Table1 as T1
    outer apply (
        select top 1 T2.[Price Date]
        from Table2 as T2
        where
            T2.[Price Date] <= T1.[Closing Date] and
            T2.[Price Date] >= dateadd(day, -5, T1.[Closing Date])
            -- you can use between, I just like >= <= syntax more
            -- T2.[Price Date] between T1.[Closing Date] and dateadd(day, -5, T1.[Closing Date])
        order by T2.[Price Date] desc
    ) as T2

=> sql fiddle demo