[英]SQL query to retrieve only one occurrence for each id
This is my (simplified) table: 这是我的(简化的)表:
id eventName seriesKey eventStart
1 Event1 5000 2012-01-01 14:00:00
2 Event2 5001 2012-01-01 14:30:00
3 Event3 5000 2012-01-01 14:50:00
4 Event4 5002 2012-01-01 14:55:00
5 Event5 5001 2012-01-01 15:00:00
6 Event6 5002 2012-01-01 15:30:00
7 Event7 5002 2012-01-01 16:00:00
I have to build a query that orders the table by eventStart (ASC)
but for each seriesKey
, I need only one occurrence. 我必须建立一个按eventStart (ASC)
对表进行eventStart (ASC)
的查询,但是对于每个seriesKey
,我只需要出现一次。
Thank you very much 非常感谢你
Try aggregating with GROUP BY and using aggregate functions like MIN(). 尝试使用GROUP BY并使用MIN()之类的聚合函数进行聚合。
SELECT seriesKey,
MIN(eventStart) eventStart
FROM events
GROUP BY seriesKey;
This results in: 结果是:
5000 2012-01-01 14:00:00.000
5001 2012-01-01 14:30:00.000
5002 2012-01-01 14:30:00.000
If your're interested in all columns from events table, not just the above two columns I choose, there's a freaky implementation in some databases (eg SQL Server) which may help you: 如果您对事件表中的所有列感兴趣,而不仅是我选择的以上两列,那么某些数据库(例如SQL Server)中有一个怪异的实现可以帮助您:
SELECT *
FROM events e1
WHERE e1.ID IN
(
SELECT TOP 1 e2.ID
FROM events e2
WHERE e2.seriesKey = e1.seriesKey
ORDER BY e2.eventStart
);
Resulting in: 导致:
1 Event1 5000 2012-01-01 14:00:00.000
2 Event2 5001 2012-01-01 14:30:00.000
6 Event2 5002 2012-01-01 14:30:00.000
If you also need the other columns associated with the key, you have two options: 如果还需要与该键关联的其他列,则有两个选择:
select *
from (
select id,
eventName,
seriesKey,
eventStart,
row_number() over (partition by seriesKey order by eventStart) as rn
from the_event_table
) t
where rn = 1
order by eventStart
or for older DBMS that do not support windowing functions: 或对于不支持窗口功能的较旧的DBMS:
select t1.id,
t1.eventName,
t1.seriesKey,
t1.eventStart
from the_event_table t1
where t1.eventStart = (select min(t2.eventStart)
from the_event_table t2
where t2.seriesKey = t1.seriesKey)
order by eventStart
you can get earlier date for each seriesKey: 您可以获得每个系列的更早日期
select * from
(
select seriesKey, min(eventStart) as mindate
group by seriesKey
)
order by mindate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.