SQL合并两列的最大值

时间:2019-03-25 10:56:16

标签: sql sql-server max

我有一个包含三列的表

+------+------------+----------+
| item |    date    | sequence |
+------+------------+----------+
| a    | 30/11/2017 |        1 |
| a    | 30/11/2017 |        2 |
| a    | 31/12/2018 |        1 |
+------+------------+----------+

我想选择一个项目日期的最大日期和最大连续性,但是

SELECT item, MAX(date), MAX(sequence of item-date-combination) FROM table GROUP BY item

不起作用,并且

SELECT item, MAX(date), MAX(sequence) FROM table GROUP BY item

为我提供了所有项目的最大顺序,而不是项-日期-组合的最大顺序。

像这样:

+------+------------+----------+
| item |    date    | sequence |
+------+------------+----------+
| a    | 31/12/2018 |        1 |
+------+------------+----------+

我该怎么办?

所以好像是这样:

SELECT maxdate_q.item, maxdate_q.maxdate, maxseq_q.maxseq FROM (
    SELECT item, MAX(date) AS maxdate FROM table GROUP BY item) AS maxdate_q
LEFT JOIN (SELECT item, date, MAX(sequence) AS maxseq FROM table GROUP by item, date) AS maxseq_q ON maxseq_q.item = maxdate_q.item AND maxseq_q.date = maxdate_q.maxdate

3 个答案:

答案 0 :(得分:2)

您可以使用窗口功能:

select t.*  -- select whatever columns you really want.
from (select t.*,
             row_number() over (partition by item order by date desc, sequence desc) as seqnum
      from t
     ) t
where seqnum = 1;

答案 1 :(得分:1)

您可以使用max()窗口功能

  SELECT item, MAX(date) over(partition by item) as Mxdate,
         MAX(sequence) over(partition by item) as MxSeq
     FROM table 

答案 2 :(得分:1)

在标准SQL中,您可以使用相关子查询:

select t.*
from table t
where t.seq = (select t1.seq
               from table t1 
               where t1.item = t.item
               order by t1.date desc, t1.seq desc
               fetch first 1 rows only
              );

某些其他DBMS具有不同的语法来限制行,例如SQL Server对MySQL使用TOP子句或LIMIT