开发者

Multiple Havings not working

开发者 https://www.devze.com 2023-01-10 17:13 出处:网络
I have a database with the following schema: IDPositionIdLeagueId 145 345 385 416 I have this sql query in Access:

I have a database with the following schema:

ID   PositionId    LeagueId
1        4            5
3        4            5
3        8            5
4        1            6

I have this sql query in Access:

 SELECT lp.PositionId
 FROM Leagues l 
 INNER JOIN Lineups lp ON (l.LeagueID = lp.LeagueId) 
 GROUP BY PositionId
 HAVING sum(iif(lp.PositionId = 4,1,0)) > 1 AND sum(iif(lp.PositionId = 8,1,0)) > 0

If I only use the left side of the Having, ie:

 HAVING sum(iif(lp.PositionId = 4,1,0)) > 1

I will get 1 results (LeagueId 5). If I use the right-side of the Having, ie:

 HAVING sum(iif(lp.PositionI开发者_如何学God = 8,1,0)) > 0

I will also get one result (LeagueId 5), but both together (like above) yields no results.


Your issue is because the SUM can't satisfy both HAVING predicates, so try using an OR:

  SELECT lp.PositionId
    FROM Leagues l 
    JOIN Lineups lp ON (l.LeagueID = lp.LeagueId) 
GROUP BY PositionId
  HAVING SUM(iif(lp.PositionId = 4,1,0)) > 1 OR SUM(iif(lp.PositionId = 8,1,0)) > 0


Aren't you grouping by positionid? So for each positionid you're asking the sum for that positionid to be >0 when the id is 4 AND 8 at the same time. Is this possible? Do you want an OR? Should you be using a different query?

GROUP BY LeagueID, for instance?


You can write a much simplified version of this query e.g.

SELECT DISTINCT 8 AS PositionId
  FROM Lineups 
 WHERE PositionId = 8 
UNION ALL
SELECT DISTINCT 4
  FROM Lineups 
 WHERE PositionId = 4
HAVING COUNT(*) > 1;
0

精彩评论

暂无评论...
验证码 换一张
取 消