输出联系日期大于订单日期的每个订单的最大联系日期

时间:2018-09-24 15:51:32

标签: 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| 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))

2 个答案:

答案 0 :(得分:1)

我们可以在此处使用ROW_NUMBER

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;

答案 1 :(得分:1)

另一种选择是将WITH TIES子句与Row_Number()配合使用

Select top 1 with ties *
 From  table1 
 Order By Row_Number() over (Partition By ID Order By contactdate Desc)