SQL - 两个查询之间的差异

时间:2017-09-19 04:05:16

标签: sql difference

我有两个SQL查询,可以获得每个国家/地区的平均温度以及每个国家/地区的平均温度:

SELECT strftime('%Y', date) as valYear, AVG(averageTemperature) 
FROM state 
WHERE country = 'Africa' 
GROUP BY valYear

SELECT strftime('%Y', date) as valYear, AVG(averageTemperature) 
FROM country 
WHERE country = 'Africa' 
GROUP BY valYear

我想要做的是计算每年州和国家之间的差异。例如:

国家数据

Year  AverageTemp
-----------------
1954  17.5
1955  18

州数据

Year  AverageTemp
-----------------
1954  15.5
1955  15

会屈服:

差分

     Year  Diff
     -----------
     1954  2
     1955  3

我尝试过这样的事情,但它没有产生正确的答案。

SELECT
    s.date, (c.averageTemperature - s.averageTemperature) AS Difference 
FROM 
    state s 
INNER JOIN 
    country c ON s.date = c.date 
WHERE
    s.country = 'Africa' AND c.country = 'Africa'

2 个答案:

答案 0 :(得分:3)

这里可能有用的一种方法是将两个查询放入子查询并在年份加入:

SELECT
    t1.valYear,
    t1.avgTemp - t2.avgTemp AS Diff
FROM
(
    SELECT
        strftime('%Y', date) AS valYear,
        AVG(averageTemperature) AS avgTemp
   FROM country
   WHERE country = 'Africa'
   GROUP BY valYear
) t1
INNER JOIN
(
    SELECT
        strftime('%Y', date) AS valYear,
        AVG(averageTemperature) AS avgTemp
    FROM state
    WHERE country = 'Africa'
    GROUP BY valYear
) t2
    ON t1.valYear = t2.valYear

上面的查询有一点黑客的感觉。为了覆盖出现在一个表而不是另一个表中的一年的情况,我们将不得不求助于完全外部联接或丑陋的联合查询。无论如何,我们可能不得不使用日历表来覆盖完全缺失的年份。我觉得更好的数据模型就是在月份级别将所有数据存储在一个表中。然后,通过汇总特定年份的所有月份,可以获得年平均值。

答案 1 :(得分:1)

SELECT s.valYear, (c.average - s.average) AS Difference 
FROM ( SELECT EXTRACT(YEAR FROM date) AS valYear, AVG(averageTemperature) AS average
       FROM state WHERE country = 'Africa' GROUP BY valYear
     ) AS s,
     ( SELECT EXTRACT(YEAR FROM date) AS valYear, AVG(averageTemperature) AS average
       FROM country WHERE country = 'Africa' GROUP BY valYear
     ) AS c
WHERE s.valYear = c.valYear