gpt4 book ai didi

mysql - 尝试显示与 ID 匹配次数不超过 3 次的匹配行。单表

转载 作者:行者123 更新时间:2023-11-29 05:50:48 27 4
gpt4 key购买 nike

我是 SQL 和 mySQL 的新手,我自学并尝试编写一个查询,向我显示 ID 列中匹配的 ID 的计数为 3 或更少的所有行。

例如:

Id       timestamp          Number            
-- --------- ---
1 0001-12-01 1001
1 0001-12-02 3520
1 0001-12-01 1002
2 0001-12-02 2152
2 0001-12-01 1005
2 0001-12-02 1250
2 0001-12-01 1007
2 0001-12-02 1536
3 0001-12-01 1009
2 0001-12-02 1305
3 0001-12-01 1010
2 0001-12-02 1125
3 0001-12-01 1107
2 0001-12-02 1108

理想情况下,结果会显示:

Id       timestamp          Number            
-- --------- ---
1 0001-12-01 1001
1 0001-12-01 1002
1 0001-12-02 3520
3 0001-12-01 1009
3 0001-12-01 1010
3 0001-12-01 1107

这会识别 ID“1”和 ID“3”都有 3 个或更少的匹配/计数 ID,并通过我设置的任何过滤器显示结果。

我已经设法编写了一个查询来计算行数并且只显示 3 或更少的计数,但是这按它们的 ID 对它们进行分组并且不显示行。看起来像这样:

select 
concat(t1.id) as 'ID',
t1.timestamp as 'timestamp',
count(t1.id) as 'Number'
from
table1 t1
where -- Curly braces are Metabase variables
t1.timestamp between {{startdate}} and {{enddate}}
group by t1.id
having count(*) < 3
order by id
limit 1000

我已经围绕 SO 和其他资源进行了一些搜索,但没有找到答案,希望有人能够帮助我或插入我朝着正确的方向前进。感谢您的帮助。

最佳答案

 SELECT t1.*
FROM YourTable t1
WHERE id IN ( SELECT t2.id
FROM YourTable t2
WHERE t2.timestamp between {{startdate}} and {{enddate}}
GROUP BY t2.id
HAVING COUNT(*) <= 3)
AND t1.timestamp between {{startdate}} and {{enddate}}
ORDER BY t1.id

关于mysql - 尝试显示与 ID 匹配次数不超过 3 次的匹配行。单表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524084/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com