试图显示匹配的ID计数3个或更少倍匹配的行。单表

问题描述 投票:1回答:3

我很新的SQL和MySQL,我是自学的,并试图写一个查询,显示我有3个或更少的ID列相匹配的ID的计数所有行。

因此,例如:

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和由任何滤波器I代替已经设置显示结果。

我已经成功地写计数行和只显示是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和其他资源的一些搜索,但都拿出了干,希望有人将能够给我一个手或在正确的方向推。任何帮助表示赞赏。

mysql count rows matching
3个回答
1
投票
 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

1
投票

你需要加入原始表在分组查询中发现的ID。

SELECT table1.*
FROM table1
JOIN (
    SELECT id
    FROM table1
    HAVING COUNT(*) <= 3
    GROUP BY id
) AS grouped ON table1.id = grouped.id

此外,您还需要使用<= 3而非< 3


0
投票

你可以使用由ID子查询COUNT(*)组之间的连接

select * from table1  t1
    inner join  (

      select id
      from table1 
      group by  id 
      having count(*) <= 3 

    ) t on t.id  = t1.id 
© www.soinside.com 2019 - 2024. All rights reserved.