SQL Count where clause

Kris B picture Kris B · Aug 9, 2010 · Viewed 10.9k times · Source

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?

Answer

Cade Roux picture Cade Roux · Aug 9, 2010

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