当我尝试将两个子查询连接在一起时,第一个查询中的值发生了变化。知道为什么吗?谢谢!
这是代码:
SELECT *
FROM ((
SELECT HOME, VISITOR, COUNT("result") AS HGOALS
FROM(
SELECT HOME, VISITOR, "result"
FROM ENGLAND
WHERE TIER = 1 AND "SEASON" >= 1980 AND "result" = 'H'
)
GROUP BY HOME, VISITOR
ORDER BY HGOALS DESC)
JOIN
(SELECT HOME, VISITOR, COUNT("result") AS AGOALS
FROM(
SELECT HOME, VISITOR, "result"
FROM ENGLAND
WHERE TIER = 1 AND "SEASON" > 1980 AND "result" = 'A'
)
GROUP BY HOME, VISITOR) USING (VISITOR, HOME))
ORDER BY AGOALS DESC;
输出部分是
Manchester United Aston Villa 5 18
Arsenal West Ham United 5 17
Arsenal Aston Villa 6 17
Manchester United Everton 12 16
Liverpool Aston Villa 8 16
但是当我只执行JOIN的第一部分时,这是
SELECT HOME, VISITOR, COUNT("result") AS HGOALS
FROM(
SELECT HOME, VISITOR, "result"
FROM ENGLAND
WHERE TIER = 1 AND "SEASON" >= 1980 AND "result" = 'H'
)
GROUP BY HOME, VISITOR
ORDER BY HGOALS DESC
结果部分是:
Manchester United Tottenham Hotspur 27
Arsenal Everton 26
Manchester United Aston Villa 26
Liverpool Tottenham Hotspur 25
Manchester United West Ham United 24
请注意
Manchester United Aston Villa 5 18
Manchester United Aston Villa 26
我应该得到的结果是26,但是当我将两个子查询连接在一起时,它变为5。 为什么呢?
答案 0 :(得分:0)
我的查询非常复杂。这不是你想要的吗?
SELECT HOME, VISITOR,
SUM(CASE WHEN result = 'H' THEN 1 ELSE 0 END) as HGOALS,
SUM(CASE WHEN result = 'A' THEN 1 ELSE 0 END) as AGOALS
FROM ENGLAND
WHERE TIER = 1 AND SEASON >= 1980
GROUP BY HOME, VISITOR
ORDER BY AGOALS DESC;
注意:您可能需要result
周围的引号,具体取决于列的定义方式。