Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Count where clause

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?

like image 436
Kris B Avatar asked Aug 09 '10 14:08

Kris B


People also ask

Can we use count in WHERE clause in SQL?

SQL COUNT( ) with where clauseThe WHERE clause can be used along with SQL COUNT() function to select specific records from a table against a given condition.

Can we use count with WHERE?

SQL SELECT COUNT with WHERE clauseSQL SELECT COUNT() can be clubbed with SQL WHERE clause. Using the WHERE clause, we have access to restrict the data to be fed to the COUNT() function and SELECT statement through a condition.

What does count (*) do in SQL?

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates. COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values.


2 Answers

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
like image 167
Cade Roux Avatar answered Sep 23 '22 13:09

Cade Roux


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 
like image 40
Scott Stafford Avatar answered Sep 24 '22 13:09

Scott Stafford