选择每个组中的最后一条记录(带内部联接)

时间:2019-03-11 07:30:24

标签: sql sql-server select group-by

有一个“事件”表,其中包含如下所示的数据:

 no  | qty | events
----------------------
001  | 10  | Printed
004  | 10  | Printed
007  | 10  | Printed
004  | 2   | Reprint

,并且有一个“ Numbers”表,其中包含如下所示的数据:

start_no |   no   | serial | expiry_date
--------------------------------------------
001      |  001   | 9311   | 2019-03-03
001      |  002   | 9312   | 2019-03-03
001      |  003   | 9313   | 2019-03-03
004      |  004   | 9314   | 2019-03-06
004      |  005   | 9315   | 2019-03-06
004      |  006   | 9316   | 2019-03-06
007      |  007   | 9317   | 2019-03-10
007      |  008   | 9318   | 2019-03-10

这是我使用的查询:

SELECT start_no, n.no, n.serial, expiry_date, qty
FROM Numbers n
INNER JOIN Events e ON n.start_no = e.no
WHERE events='Printed'

我需要查询将返回以下结果:

start_no |   no   | serial | expiry_date
--------------------------------------------
001      |  003   | 9313   | 2019-03-03
004      |  006   | 9316   | 2019-03-06
007      |  008   | 9318   | 2019-03-10

我该怎么做?

2 个答案:

答案 0 :(得分:0)

ise row_number()

select * from
(
SELECT start_no, n.no, w.serial, expiry_date, qty,
row_number() over(partition by start_no order by w.serial desc) as rn
FROM Numbers n INNER JOIN Events e ON n.start_no = e.no
WHERE events='Printed'
)A where rn=1

答案 1 :(得分:0)

使用row_number()窗口功能

select * from 
(SELECT start_no, n.no, w.serial, expiry_date, qty
,row_number() over(partition by start_no order by no desc) rn
FROM Numbers n
INNER JOIN Events e ON n.start_no = e.no
WHERE events='Printed'
) a where a.rn=1