我有一个有三列的表
+------+------------+----------+
| 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
您可以使用窗口功能:
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;
你可以使用max()
窗口功能
SELECT item, MAX(date) over(partition by item) as Mxdate,
MAX(sequence) over(partition by item) as MxSeq
FROM table
在标准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服务器使用TOP
子句或LIMIT
用于MySQL。