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?
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With