[英]SQL query for finding all individual records where count > 2
So I could not find any solution for this.所以我找不到任何解决方案。 I've seen many ORDER BY and HAVING solutions, which are close, but do not fully deliver what I'm looking for.
我见过许多 ORDER BY 和 HAVING 解决方案,它们很接近,但不能完全提供我正在寻找的东西。
I have this:我有这个:
SELECT *
FROM t1
WHERE t1.placed > '2020-12-01' AND t1.placed < '2020-12-02'
GROUP BY t1.account
HAVING count(t1.account) > 2;
Now this reflects exactly the rows I want to see, but I want them not grouped together.现在这正好反映了我想看到的行,但我不希望它们组合在一起。 I want the database to give me all the individual rows.
我希望数据库给我所有单独的行。 Now I tried removing the GROUP BY, but that just doesn't work.
现在我尝试删除 GROUP BY,但这不起作用。 So how can I get the same information as above, but shown as individual rows instead of grouped?
那么如何获得与上述相同的信息,但显示为单独的行而不是分组?
Maybe with a sub query (for join) you can solve it easily也许使用子查询(用于连接)您可以轻松解决它
select a.*
from table a
inner join (
select itemID, Count(*)
from table
where placed > '2020-12-01' and placed < '2020-12-02'
group by itemID
having Count(*) > 2
) b on a.ItemID = b.itemID
I want the database to give me all the individual rows
我希望数据库给我所有单独的行
This sounds like exists
instead of aggreation:这听起来像是
exists
而不是聚合:
select *
from mytable t
where
placed > '2020-12-01'
and placed < '2020-12-02'
and exists (
select 1
from mytable t1
where
t1.account = t.account
and t1.placed > '2020-12-01'
and t1.placed < '2020-12-02'
and t1.placed <> t.placed
)
This brings entire records whose account appears more than once.这会带来其帐户出现多次的完整记录。 An index on
(account, placed)
might help this query. (account, placed)
上的索引可能有助于此查询。
You can also use window functions, if your database supports them:如果您的数据库支持,您还可以使用 window 函数:
select *
from (
select t.*, count(*) over(partition by account) as cnt
from mytable t
where placed > '2020-12-01' and placed < '2020-12-02'
) t
where cnt > 1
You could use a common table expression to retrieve the required account and then join it again with the accounts table您可以使用公用表表达式来检索所需的帐户,然后再次将其与帐户表联接
with accountids(account) as
(select account
from accounttable
where placed > '2020-12-01' and placed < '2020-12-02'
group by account
having count(account) > 2)
select a.*
from accountids ids inner join accounttable a on ids.account = a.account
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.