【问题标题】:Select the last record in each group (With inner join)选择每个组中的最后一条记录(使用内部连接)
【发布时间】:2019-03-11 07:30:23
【问题描述】:

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

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

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

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

我该怎么做?

【问题讨论】:

    标签: sql sql-server select group-by


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 2018-06-28
        相关资源
        最近更新 更多