SQL:将分区用作总和

时间:2016-11-30 16:00:39

标签: sql postgresql

我有一个简单的查询:

SELECT
    price_band
    ,device
    ,SUM(requests) as requests
From database.price_band_stats
WHERE
    day = '2016-10-31'
    AND product_id = 6584
    and device IN ('Desktop', 'Android')    
GROUP BY
    price_band
    ,device

返回一个表格如下:

|price_band | device  | requests
0             Android   149007
0.01          Android   466467
0.05          Android   520661
0.1           Android   487273
0             Desktop   319786
0.01          Desktop   1485894
0.05          Desktop   1693395
0.1           Desktop   1547485

我想调整代码以添加额外的列。新列将对给定设备的所有具有大于或等于价格带的请求求和。例如,如果我们在Android上采用0.05的价格区间,我想要Android的所有请求的总和,价格范围为0.05或更高(即0.05和0.1)

因此表格如下:

price_band      device     requests    request_above_price_band
0               Android    149007      1623408
0.01            Android    466467      1474401
0.05            Android    520661      1007934
0.1             Android    487273      487273
0               Desktop    319786      5046560
0.01            Desktop    1485894     4726774
0.05            Desktop    1693395     3240880
0.1             Desktop    1547485     1547485

1 个答案:

答案 0 :(得分:0)

您应该使用window function SUM with ORDER BY DESC and partition

WITH T AS
( SELECT
    price_band
    ,device
    ,SUM(requests) as requests
 From database.price_band_stats
 WHERE
    day = '2016-10-31'
    AND product_id = 6584
    and device IN ('Desktop', 'Android')    
 GROUP BY
    price_band,device
)
SELECT
 price_band, 
 device, 
 requests,
 SUM(requests) OVER (PARTITION BY device  ORDER BY price_band DESC) 
    as request_above_price_band 
 FROM T
ORDER BY device,price_band

SQLFiddle demo