SQLite将上周列添加到当前周

时间:2016-09-03 14:53:59

标签: sqlite

我有以下数据

   Week    Country       Quantity     Price 
    1       Sweden          2          $10
    1       Germany         3          $20
    2       Sweden          10         $20

我想做的是这样的事情:

 Country Quantity Price  Current Week Revenue  Past Week Revenue 
 Sweden   30      100         300        3000    2000

如果我只是做国家,数量,价格,当前周我使用

SELECT Country, sum(uantity), sum(price), sum(price*quantity) as         
    revenue
    from dataset where Week = 1 Group by Country.

但是,由于where语句将数据限制为仅一周,我对如何添加前一周感到茫然?

谢谢!

2 个答案:

答案 0 :(得分:0)

使用条件聚合。也就是说,将条件从where移动到sum()聚合函数:

SELECT Country,
       SUM(CASE WHEN Week = 1 THEN quantity END) as quantity_1, 
       SUM(CASE WHEN Week = 1 THEN price END) as price_1,
       SUM(CASE WHEN Week = 1 THEN price*quantity END) as revenue_1,
       SUM(CASE WHEN Week = 2 THEN quantity END) as quantity_2, 
       SUM(CASE WHEN Week = 2 THEN price END) as price_2,
       SUM(CASE WHEN Week = 2 THEN price*quantity END) as revenue_2
FROM dataset d
WHERE Week IN (1, 2)
GROUP BY Country;

答案 1 :(得分:0)

在一般情况下,使用correlated subquery来循环前一周的数据:

SELECT Country,
       SUM(Quantity * Price) AS Revenue,
       (SELECT SUM(Quantity * Price)
        FROM dataset AS PrevWeek
        WHERE PrevWeek.Week = dataset.Week - 1
          AND PrevWeek.Country = dataset.Country
       ) AS "Past Week Revenue"
FROM dataset
GROUP BY Country;