SQL Count where clause

試著忘記壹切 提交于 2019-12-10 14:32:42

问题


I have the the following SQL statement:

 SELECT        [l.LeagueId] AS LeagueId, [l.LeagueName] AS NAME, [lp.PositionId]
 FROM            (Leagues l INNER JOIN
                     Lineups lp ON l.LeagueId = lp.LeagueId)
 WHERE        (lp.PositionId = 1) OR
                     (lp.PositionId = 3) OR
                     (lp.PositionId = 2)

What I really need is to get the rows where the count of the position is greater than a number. Something like:

 SELECT        [l.LeagueId] AS LeagueId, [l.LeagueName] AS NAME, [lp.PositionId]
 FROM            (Leagues l INNER JOIN
                     Lineups lp ON l.LeagueId = lp.LeagueId)
 WHERE        Count(lp.PositionId = 1) > 2 OR
                     Count(lp.PositionId = 3) > 6 OR
                     Count(lp.PositionId = 2) > 3

Is there any way to do this in SQL?


回答1:


How about this?:

SELECT        [l.LeagueId] AS LeagueId, [l.LeagueName] AS NAME
 FROM            (Leagues l INNER JOIN
                     Lineups lp ON l.LeagueId = lp.LeagueId)
 GROUP BY [l.LeagueId], [l.LeagueName]
 HAVING        SUM(CASE WHEN lp.PositionId = 1 THEN 1 ELSE 0 END) > 2 OR
                     SUM(CASE WHEN lp.PositionId = 3 THEN 1 ELSE 0 END) > 6 OR
                     SUM(CASE WHEN lp.PositionId = 2 THEN 1 ELSE 0 END) > 3



回答2:


HAVING is the keyword you're looking for:

SELECT        [l.LeagueId] AS LeagueId, [l.LeagueName] AS NAME, [lp.PositionId]
FROM            (Leagues l INNER JOIN
                     Lineups lp ON l.LeagueId = lp.LeagueId)
GROUP BY lp.PositionId, l.LeagueName
HAVING lp.PositionId = 1 AND COUNT(*) > 2 
       OR lp.PositionId = 2 AND COUNT(*) > 3 
       OR lp.PositionId = 3 AND COUNT(*) > 6 


来源:https://stackoverflow.com/questions/3440857/sql-count-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!