选择最新日期的唯一记录

时间:2018-09-06 21:18:55

标签: sql tsql

我正在尝试获取T-SQL查询,以从表中读取订单并显示一段时间(即最近7天)内公司的最新订单。如果公司在此期间下了多个订单,则只会显示最新的订单。我下面的查询在其后产生结果。我想得到的结果就是那张桌子。

select StoreID, OrderID, ModDate
    from Orders

    where ModDate > (getdate() - 7)
    order by StoreID desc, ModDate desc

上述SQL的输出产生:

StoreID  OrderID  ModDate
=======  =======  =======================
6093     188954   2018-08-31 12:56:09.690
6093     188883   2018-08-30 13:54:50.520
6092     189215   2018-09-06 11:01:35.257
5994     189182   2018-09-05 22:20:25.907
5994     189159   2018-09-05 17:11:22.200
5994     189169   2018-09-05 17:06:16.003
5994     189163   2018-09-05 16:04:23.683
5994     189123   2018-09-05 13:13:16.523
5994     189124   2018-09-05 13:10:30.750

我想要的输出:

StoreID  OrderID  ModDate
=======  =======  =======================
6093     188954   2018-08-31 12:56:09.690
6092     189215   2018-09-06 11:01:35.257
5994     189182   2018-09-05 22:20:25.907

我尝试使用 distinct ,希望它只会选择StoreID(即选择不同的StoreID ...),但没有任何区别。我想让该查询正常工作的原因是什么?在最坏的情况下,我可以按原样使用数据,并且C#不会显示重复的StoreID,但是我希望从好的SQL中获得正确的输出。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以尝试按StoreID列然后按order by ModDate desc来创建行号

然后获取rn = 1数据。

CREATE TABLE T(
   StoreID int,
   OrderID int,
   ModDate datetime
);




insert into t values (6093,188954,'2018-08-31 12:56:09.690');
insert into t values (6093,188883,'2018-08-30 13:54:50.520');
insert into t values (6092,189215,'2018-09-06 11:01:35.257');
insert into t values (5994,189182,'2018-09-05 22:20:25.907');
insert into t values (5994,189159,'2018-09-05 17:11:22.200');
insert into t values (5994,189169,'2018-09-05 17:06:16.003');
insert into t values (5994,189163,'2018-09-05 16:04:23.683');
insert into t values (5994,189123,'2018-09-05 13:13:16.523');
insert into t values (5994,189124,'2018-09-05 13:10:30.750');

查询1

select StoreID,OrderID,ModDate 
from (
    SELECT *,row_number() OVER(PARTITION BY StoreID  order by ModDate desc) rn
    FROM T
)t1
where rn = 1

Results

| StoreID | OrderID |                  ModDate |
|---------|---------|--------------------------|
|    5994 |  189182 | 2018-09-05T22:20:25.907Z |
|    6092 |  189215 | 2018-09-06T11:01:35.257Z |
|    6093 |  188954 |  2018-08-31T12:56:09.69Z |