2017-09-19 168 views
1

我有獲得國家狀態的國家和平均溫度總體來說,每一年的兩個SQL查詢之間的區別州和國家每年。因此,例如:SQL兩個查詢

國家數據

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' 

回答

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
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