我有一个包含UserId
,UserName
列的表格,如:
UserName UserId
sakthi 50
sakthi 50
sakthi 50
sakthi 50
ganesh 40
ganesh 40
ganesh 40
我想分组count(userId)> 3
我想要群组记录,如:
UserName UserId
sakthi 50
ganesh 40
ganesh 40
ganesh 40
答案 0 :(得分:1)
好吧,您可能会发现更多可读方式,具体取决于您的dbms(例如,sql server中的cte)。您还可以创建一个包含"多于3个副本")的视图。
但是一种方法可以是使用UNION ALL(UNION会删除重复项)
select
UserName, UserId
from table
group by UserName, UserId
having count(*) > 3
union all
select t.UserName, t.UserId
from table t
where not exists (select null
from table t1
where t1.UserName = t.UserName and t1.UserId = t.UserId
group by t1.UserName, t1.UserId
having count(*) > 3)
请参阅SqlFiddle
答案 1 :(得分:1)
您需要将SELECT
声明分成两部分,并UNION ALL
将它们放在一起。
这样的事情(显然会改变你的数据):
SELECT UserName, UserId
FROM Tbl
GROUP BY UserName, UserId
HAVING COUNT(*) > 3
UNION ALL
SELECT UserName, UserId
FROM Tbl
WHERE UserId NOT IN
(
SELECT UserId
FROM Tbl
GROUP BY UserName, UserId
HAVING COUNT(*) > 3
)