2017-05-26 87 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

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

相关问题