我有表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与closeDt然后有一个新的appid,requestDt大于CloseDt。
我是这样做的:
从表1中选择*
在t.customer = o.customer
上加入旧o和t.appId<> o.appid
和t.requestDt> o.closeddt
但这会让我回头:
CUSTOMER REQUESTDT CLOSEDDT APPID
1 201404 (null)
2 201405 (null)
2 201409 (null)
这基本上是正确的,但是当客户在CloseDt之后还有两个带有RequestDt的appId我想只选择一个更接近RequestDt到CloseDt的那个...我不知道该怎么做.. :(
结果应该是这样的:
CUSTOMER REQUESTDT CLOSEDDT APPID
1 201404 (null)
2 201405 (null)
希望它清楚:) 谢谢!
答案 0 :(得分: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