我有以下SQL语句:
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)
我真正需要的是获取位置计数大于数字的行。类似的东西:
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
有没有办法在SQL中执行此操作?
答案 0 :(得分:9)
这个怎么样?:
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
答案 1 :(得分:7)
HAVING是您正在寻找的关键字:
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