选择具有最新日期SQL的记录

时间:2019-01-31 12:19:23

标签: sql sql-server

我的SQL中有以下条目:

Reference    | Clearing Date | Posting Date | Payment Date
LVR181035902 | 2018-11-23    | 2017-12-23   | 2018-10-23
LVR181035902 | 2018-11-28    | 2018-11-23   | 2018-08-23
LVR181035902 | 2018-11-23    | 2017-12-23   | 2018-10-23

我想返回带有最新Clearing Date的条目,所以我的结果将是:

Reference    | Clearing Date | Posting Date | Payment Date
LVR181035902 | 2018-11-28    | 2018-11-23   | 2018-08-23

我尝试了以下查询:

SELECT reference, clearing_date= max(clearing_date) FROM trdinvoices WHERE reference='LVR181035902' GROUP BY reference

将返回:

[
    {
        "reference": "LVR181035902",
        "clearing_date": "2018-11-28T00:00:00.000Z"
    }
]

但是我希望结果像这样返回整行:

[
    {
        "reference": "LVR181035902",
        "clearing_date": "2018-11-28T00:00:00.000Z",
        "posting_date": "2018-11-23T00:00:00.000Z",
        "payment_date": "2018-08-23T00:00:00.000Z"
    }
]

我该怎么做?谢谢您的时间!

5 个答案:

答案 0 :(得分:2)

您可以按照“结算日期”以降序对数据进行排序,并可以返回结果集:

  -- sqlserver
Select Top 1 * From dbo.Table Order By ClearingDate Desc;
 -- if you want to select a particular row based on a key
Select Top 1 * From dbo.Table Where Reference = 'LVR181035902' Order By ClearingDate Desc;

-- add 'Limit' for MySQL

答案 1 :(得分:1)

另一种方法。

SELECT reference, 
       clearing_date, 
       posting_date, 
       payment_date 
FROM   (SELECT *, 
               Row_number() 
                 OVER(partition BY reference 
                   ORDER BY clearing_date DESC) rn 
        FROM   trdinvoices 
        WHERE  reference = 'LVR181035902') t 
WHERE  rn = 1 

答案 2 :(得分:1)

另一种select * from ( select *,row_number()over(partition by reference order by clearing_date desc)rn ) t where t.rn=1 窗口功能

  deleteUser = async (id) => {
         let url = `https://contact-browser.herokuapp.com/contact/${id}`;
        const deleted = await fetch(url, {method: 'delete'}).then(resp => console.log(resp));
        if(deleted){
             await this.fetchData();
        }
   };

答案 3 :(得分:1)

Select reference, clearing_date=max(clearing_date), posting_date, payment_date from trdinvoices Group By reference, posting_date, payment_date having reference = 'LVR181035902'

使用上述查询。

答案 4 :(得分:0)

具有良好性能的方法使用了相关的子查询:

select t.*
from t
where t.clearing_date = (select max(t2.clearing_date) from t t2 where t2.reference = t.reference);

尤其是,这可以利用(reference, clearing_date)上的索引。