我有桌子
GLId Id DonarId
----------- ----------- -----------
1 1 1
2 1 2
3 2 1
4 2 2
5 3 1
6 3 2
7 4 1
8 4 2
9 5 1
10 5 2
现在,我想找到那些在donarId列中不存在并且其计数(donarid)小于8的id
我写了一个查询
SELECT g.id
FROM gamestar g
LEFT JOIN gamestar gs
ON g.id = gs.donarid
GROUP BY g.id,
g.glid
HAVING Count(gs.donarid) < 8
ORDER BY g.glid
但它会产生重复的值。
结果看起来像
ID
-----------
1
1
2
2
3
3
4
4
等等。
等待帮助。谢谢
答案 0 :(得分:0)
您可以使用DISTINCT
:
SELECT DISTINCT g.id
FROM gamestar g
LEFT JOIN gamestar gs
ON g.id = gs.donarid
GROUP BY g.id,
g.glid
HAVING Count(gs.donarid) < 8
ORDER BY g.glid
答案 1 :(得分:0)
您似乎正在寻找在donar id列中出现少于8次的ID。
select g.id
from gamestar g
where g.donarid not in (select donarid from gamestar)
group by g.id
having count(*) < 8
答案 2 :(得分:0)
试试这个
SELECT g.id
FROM gamestar g
LEFT JOIN gamestar gs
ON g.id = gs.donarid
GROUP BY g.id
HAVING Count(gs.donarid) < 8
答案 3 :(得分:0)
;WITH cte AS
(
SELECT g.glid, g.id,
COUNT(1) OVER (PARTITION BY gs.donarid, g.glid) AS cn
FROM gamestar g LEFT JOIN gamestar gs ON g.id = gs.donarid
)
SELECT Id
FROM cte
WHERE cn < 8
GROUP BY Id