0

当我尝试将两个子查询连接在一起时,第一个查询中的值发生了变化。知道为什么吗?谢谢!

这是代码:

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。为什么?

4

1 回答 1

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,具体取决于列的定义方式。

于 2017-10-15T22:23:12.013 回答