Sql server 如果联系日期大于订单日期,则输出每个订单的最大联系日期
我想输出每个订单的最大联系日期,其中联系日期大于订单日期。我有一张这样的桌子:Sql server 如果联系日期大于订单日期,则输出每个订单的最大联系日期,sql-server,Sql Server,我想输出每个订单的最大联系日期,其中联系日期大于订单日期。我有一张这样的桌子: ID | orderdate | value1| value2 | orderid |country |customerID | partnerID | contactdate | 1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2016-08-01 01:39:37.997| 1171| 20
ID | orderdate | value1| value2 | orderid |country |customerID | partnerID | contactdate |
1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2016-08-01 01:39:37.997|
1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2017-01-26 02:07:01.990|
1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2017-10-24 02:44:38.117|
1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2018-04-24 01:06:16.630
1171| 2017.10.27 | 287 |100 | 52912605|DE |211126498 | 24020898970| 2016-08-01 01:39:37.997
1171| 2017.10.27 | 287 |100 | 52912605|DE |211126498 | 24020898970| 2017-01-26 02:07:01.990
1171| 2017.10.27 | 287 |100 | 52912605|DE |211126498 | 24020898970| 2017-10-24 02:44:38.117
1171| 2017.10.27 | 287 |100 | 52912605|DE |211126498 | 24020898970| 2018-04-24 01:06:16.630
我希望得到以下结果:
1171| 2016.08.11 | 404 |170 | 52769275|DE |211126498 | 24020898970| 2016-08-01 01:39:37.997
1171| 2017.10.27 | 287 |100 | 52912605|DE |211126498 | 24020898970| 2017-10-24 02:44:38.117
我这样试过,这辆车不正常:
select a.ID,
a.orderdate,
a.value1,
a.value2,
a.orderid,
a.country,
a.customerID,
a.PARTNERid,
cast(MAX(contactdate) as date) as contactdate
FROM table1 a
group by a.ID, a.orderdate, a.value1, a.value2, a.orderid, a.country, a.customerID, a.PARTNERid
having cast(MAX(a.contactdate) as date) < cast(a.orderid as date))
选择a.ID,
a、 订单日期,
a、 价值1,
a、 价值2,
a、 医嘱ID,
a、 国家,,
a、 客户ID,
a、 PARTNERid,
转换(最大(contactdate)为日期)为contactdate
来自表1 a
按a.ID、a.orderdate、a.value1、a.value2、a.orderid、a.country、a.customerID、a.PARTNERid分组
具有cast(MAX(a.contactdate)作为日期)
我们可以在这里使用行号
:
SELECT ID, orderdate, value1, value2, ordered, country, customerID, PARTNERid,
contractdate
FROM
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY orderid ORDER BY contractdate DESC) rn
FROM table1
WHERE CAST(contactdate AS date) > CAST(orderid AS date)
) t
WHERE rn = 1;
另一种选择是将
WITH TIES
子句与行号()配合使用
Select top 1 with ties *
From table1
Order By Row_Number() over (Partition By ID Order By contactdate Desc)