1

我有桌子

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 列中且 count(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

等等。

等待帮助。谢谢

4

4 回答 4

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
于 2012-12-12T00:26:57.853 回答
0

您似乎正在寻找出现次数少于 8 次的 id,它们在 donar id 列中是 no。

select g.id
from gamestar g
where g.donarid not in (select donarid from gamestar)
group by g.id
having count(*) < 8
于 2012-12-11T19:01:35.407 回答
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 

SQL文件

于 2012-12-11T19:24:15.847 回答
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 
于 2012-12-11T18:59:50.737 回答