我需要帮助创建一个查询来为我提供正确的输出。
我有一个包含示例输出的表格:
身份证号码 | 小时 |
---|---|
1 | 09:00 |
1 | 11:00 |
2 | 09:00 |
2 | 11:00 |
3 | 09:00 |
3 | 10:00 |
3 | 11:00 |
4 | 09:00 |
4 | 11:00 |
5 | 11:00 |
输出应如下所示:
CNT_ID | 小时 |
---|---|
4 | 09:00 |
1 | 11:00 |
应忽略所有其他条目。
如何创建此查询我已经用 MIN(HOUR) 尝试过,但这不起作用,因为如果存在仅 11:00 的 ID,则不会显示。
如果我理解正确的话,你想要这个:花最少的时间,数一下它的 ID。在接下来的至少一个小时内,计算其 ID,除了我们已经计算过的 ID。花接下来的至少一个小时,计算它的 ID,除了我们已经计算过的 ID。
因此,查看一小时并使用
NOT IN
或 NOT EXISTS
从较早一小时发生的计数中删除 ID。
一种方法,首先获取小时数,然后在子查询中计数:
with hours as (select distinct hour from mytable)
select
hour,
(
select count(*)
from mytable t
where t.hour = h.hour
and t.id not in
(
select id
from mytable before
where before.hour < t.hour
)
) as cnt
from hours h
order by hours;
另一个,剥离我们不想立即计数的行:
with data as
(
select hour, id
from mytable t
where id not in
(
select id
from mytable before
where before.hour < t.hour
)
)
select hour, count(*) as cnt
from data
group by hour
order by hour;
第二个选项是我的偏好,因为我们只聚合表格一次。
您可以使用以下内容,
select id, min(hour) from mytable
group by id
确保您的“小时”列处于“时间”/“时间戳”类型。