2017-05-26 84 views
0

我需要比較同一表中同一列中的2017年和2016年之間的數據。如何比較同一表中同一列中的數據

現在我用2個查詢:

第一次查詢:

SELECT 
     SUM(a.netamt) AS netamt2017, b.store_name, c.budget 
    FROM 
     site_sales a 
    JOIN 
     site_store b ON b.storenum = a.storenum 
    JOIN 
     site_kpimthslsbgt c ON b.storenum = c.storenum 
    WHERE 
     c.busidate = '2017-01' 
     AND a.busidate >= '2017-01-01' 
     AND a.busidate <= '2017-01-15' 
    GROUP BY 
     a.storenum 

這對於找到netamt 2017年

第二查詢:

SELECT 
     SUM(a.netamt) AS netamt2016, b.store_name, c.budget 
    FROM 
     site_sales a 
    JOIN 
     site_store b ON b.storenum = a.storenum 
    JOIN 
     site_kpimthslsbgt c ON b.storenum = c.storenum 
    WHERE 
     c.busidate = '2017-01' 
     AND a.busidate >= '2016-01-01' 
     AND a.busidate <= '2016-01-15' 
    GROUP BY 
     a.storenum 

這種尋找「Netamt 2016 」。

我需要這2個查詢結合起來,形成該表:

Here is example for the output

回答

0

只需使用sum(case when ... then ... else ... end)語法:

SELECT 
    SUM(CASE WHEN a.busidate BETWEEN '2016-01-01' AND '2016-01-15' THEN a.netamt ELSE 0 END) as netamt2016, 
    SUM(CASE WHEN a.busidate BETWEEN '2017-01-01' AND '2017-01-15' THEN a.netamt ELSE 0 END) as netamt2017, 
    b.store_name, 
    c.budget 
FROM site_sales a JOIN site_store b ON b.storenum = a.storenum 
JOIN site_kpimthslsbgt c ON b.storenum = c.storenum 
WHERE c.busidate = '2017-01' 
GROUP BY a.storenum 

注:因爲你使用GROUP BYb.store_namec.budget沒有被彙總,所以這兩列是毫無意義的。

+0

非常感謝您的回答。它工作得很好! :) –