2014-11-03 18 views
-1

我有表table1:尋找更接近日至特定日期

CREATE TABLE Table1 
    ([Customer] int, [RequestDt] int, [ClosedDt] int, [AppId] int) 
; 

INSERT INTO Table1 
    ([Customer], [RequestDt], [ClosedDt], [AppId]) 
VALUES 
    (1, 201401, 201403, 1), 
    (1, 201403, NULL, 2), 
    (1, 201404, NULL, 3), 
    (2, 201402, 201404, 4), 
    (2, 201405, NULL, 5), 
    (2, 201409, NULL, 6), 
    (3, 201403, NULL, 7) 
; 

,我想選擇哪些客戶擁有的AppID與閉T,然後有一個新的appid與requestDt更大然後閉T。

我沒有使用此:

SELECT * FROM表1牛逼

加入舊的O上t.customer = o.customer

和t.appId <> o.appid

和t.requestDt> o.closeddt

但是,這將返回我:

CUSTOMER REQUESTDT CLOSEDDT APPID 
1   201404  (null)  
2   201405  (null)  
2   201409  (null)  

這基本上是正確的,但是當客戶有兩個以上的appid與RequestDt閉T後我要選擇具有接近RequestDt到閉T只有一個......我不知道如何要做到這一點.. :(

結果應該是這樣的:

CUSTOMER REQUESTDT CLOSEDDT APPID 
1   201404  (null)  
2   201405  (null)  

希望其明確的:) 謝謝!

+0

我會強烈建議使用日期數據類型存儲日期,而不是整數。幫我理解這裏的邏輯。你爲什麼期待APPID 3和5?下一個RequestDt是否大於ClosedDt? – 2014-11-03 20:55:49

+0

對不起,我不期待id 3和5,問題得到糾正。 – Nightmaresux 2014-11-04 06:10:46

回答

1

如果你不希望的AppId然後加入min()功能,以您的原始查詢應該是足夠了:

select t.Customer, min(t.RequestDt) Requestdt, t.ClosedDt, null as Appid 
from Table1 t 
join old o on t.customer = o.customer 
and t.appId <> o.appid 
and t.requestDt > o.closeddt 
group by t.Customer, t.ClosedDt 

在你編輯它包含的AppId太多的問題,和下面的查詢會給你即:

select 
    t2.customer, 
    t2.requestdt, 
    t2.closeddt, 
    t2.appid 
from table1 t1 
outer apply (  
    select top 1 * 
    from Table1 
    where RequestDt > t1.closeddt and Customer = t1.Customer 
    ) t2 
where t1.closeddt is not null 

我幾乎可以肯定一定有更好的方法來做到這一點,但我的大腦就不會在目前的工作;)

這還應該工作,如果APPID被下令:以上

select 
    t2.Customer, 
    RequestDt = min(t2.RequestDt), 
    ClosedDt = min(t2.ClosedDt), 
    Appid  = min(t2.AppId) 
from Table1 t1 
left join Table1 t2 on t1.Customer = t2.Customer and t1.ClosedDt < t2.RequestDt 
where t1.ClosedDt is not null 
group by t2.Customer 

的查詢提供了以下的輸出:

Query 1: 
Customer Requestdt ClosedDt Appid 
----------- ----------- ----------- ----------- 
1   201404  NULL  NULL 
2   201405  NULL  NULL 

Query 2: 
customer requestdt closeddt appid 
----------- ----------- ----------- ----------- 
1   201404  NULL  3 
2   201405  NULL  5  

Query 3: 
Customer RequestDt ClosedDt appid 
----------- ----------- ----------- ----------- 
1   201404  NULL  3 
2   201405  NULL  5