选择最新的3条记录

时间:2018-10-30 14:10:34

标签: sql sql-server tsql sql-server-2014

使用SQL Server2014。我有列出唯一标识符,销售数据和销售价格的数据。我想将每个唯一ID的最近3次销售提取到VIEW中。

数据示例:

+------+-----------+------------+-------------+
|  ID  | UNIQUE_ID |  SaleDate  | SalePrice   |
+------+-----------+------------+-------------+
| 8210 | 1-5       | 2015-09-29 |         0   |
| 8211 | 1-6       | 2016-11-01 |    485672   |
| 8212 | 1-7       | 1994-06-24 |    120000   |
| 8213 | 1-1       | 1996-09-06 |    170000   |
| 8214 | 1-1       | 2000-01-28 |    265000   |
| 8215 | 1-1       | 2013-10-02 |    305000   |
| 8216 | 1-1       | 2015-11-20 |   1425000   |
| 8217 | 1-3       | 1994-01-12 |         1   |
| 8218 | 1-3       | 2001-04-30 |         1   |
| 8219 | 1-3       | 2004-09-30 |         0   |
+------+-----------+------------+-------------+

视图中的结果将列出每个唯一ID,然后列出6个字段:

  1. SaleDate1
  2. SalePrice1
  3. SaleDate2
  4. SalePrice2
  5. SaleDate3
  6. SalePrice3

任何提示表示赞赏。

3 个答案:

答案 0 :(得分:3)

您可以使用row_number()

SELECT t.*
FROM (SELECT t.*,
             ROW_NUMBER() OVER (PARTITION BY UNIQUE_ID ORDER BY SaleDate DESC, SalePrice DESC) AS Seq
      FROM table t
     ) t
WHERE Seq <= 3;

答案 1 :(得分:2)

您可以使用窗口函数来过滤数据,然后使用条件聚合来获取所需的6列:

declare @tmp table(ID int, UNIQUE_ID varchar(50), SaleDate date, SalePrice int)

insert into @tmp values
     (8210, '1-5','2015-09-29', 0      )
    ,(8211, '1-6','2016-11-01', 485672 ) 
    ,(8212, '1-7','1994-06-24', 120000 ) 
    ,(8213, '1-1','1996-09-06', 170000 ) 
    ,(8214, '1-1','2000-01-28', 265000 ) 
    ,(8215, '1-1','2013-10-02', 305000 ) 
    ,(8216, '1-1','2015-11-20', 1425000)  
    ,(8217, '1-3','1994-01-12', 1      )
    ,(8218, '1-3','2001-04-30', 1      )
    ,(8219, '1-3','2004-09-30', 0      )

SELECT t.UNIQUE_ID
    ,max(case when t.Seq = 1 then SaleDate  else null end) as SaleDate1
    ,sum(case when t.Seq = 1 then SalePrice else null end) as SalePrice1
    ,max(case when t.Seq = 2 then SaleDate  else null end) as SaleDate2
    ,sum(case when t.Seq = 2 then SalePrice else null end) as SalePrice2
    ,max(case when t.Seq = 3 then SaleDate  else null end) as SaleDate3
    ,sum(case when t.Seq = 3 then SalePrice else null end) as SalePrice3
FROM (SELECT x.*,
        ROW_NUMBER() OVER (PARTITION BY UNIQUE_ID 
            ORDER BY SaleDate DESC, SalePrice DESC) AS Seq
      FROM @tmp x
     ) t
WHERE t.Seq < 4
group by t.UNIQUE_ID

结果:

enter image description here

答案 2 :(得分:0)

以下查询返回每件商品最近出售的3行

select * from ( select UNIQUE_ID,SaleDate,SalePrice,rank() over (partition by UNIQUE_ID order by SaleDate desc) as rnk from salestable ) where rnk<4