【问题标题】:SQL: Using a partition as a condition in a sumSQL:使用分区作为求和的条件
【发布时间】:2016-12-08 14:55:23
【问题描述】:

我有一个简单的查询:

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,我想要价格区间为 0.05 或更高(即 0.05 和 0.1)的所有 Android 请求的总和

所以表格看起来像:

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

【问题讨论】:

  • 我不明白,但一个建议是创建 2 个临时表。第一个将保存您现有请求的结果,第二个将保存您要添加的额外列的结果。然后,您可以内部连接 ​​2 个临时表。
  • 此位:“价格区间大于或等于相关价格区间的位置。”特别弯曲
  • 嗨。我认为结果表可能有助于澄清这一点。如果我们以 Android 上的价格区间 0.05 为例,我想要价格区间为 0.05 或更高(即 0.05 和 0.1)的所有 Android 请求的总和。

标签: sql postgresql


【解决方案1】:

你应该使用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

【讨论】:

  • 嗨。这几乎可以工作......在创建 T 的 WITH 部分中,我们在 Group By 中也需要“设备”。一旦我把它完美地投入使用!您能否添加此更改,我会将其标记为正确答案。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2011-10-12
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多