【问题标题】:SUM value group by columns but do not 'aggregate' possible?SUM 值按列分组,但不能“聚合”?
【发布时间】:2019-04-23 09:49:07
【问题描述】:

我想根据 2 个不同的值来总结达到阈值的次数:日期和项目。

Redshift 给我一个错误,要求在 group by 中添加更多列(我不希望在 group by 中:“列必须出现在 group by 子句中或用于聚合函数中”)。

会出现的另一个问题是代码会聚合我的列,我想复制 SUM 数字。

我有什么

|------------|--------|------------|
| item_type  | date   |thresh_rchd |
|------------|--------|------------|
|    baby    |monday  |      2     |
|------------|--------|------------|
|    tom     |monday  |      6     |
|------------|--------|------------|
|    baby    |monday  |      8     |
|------------|--------|------------|
|    baby    |tuesday |      4     |
|------------|--------|------------|

我想要什么:

|------------|--------|------------|-------------|
| item_type  | date   |thresh_rchd |total thresh |
|------------|--------|------------|-------------|
|    baby    |monday  |      2     |     10      |
|------------|--------|------------|-------------|
|    tom     |monday  |      6     |      6      |
|------------|--------|------------|-------------|
|    baby    |monday  |      8     |     10      |
|------------|--------|------------|-------------|
|    baby    |tuesday |      4     |      4      |
|------------|--------|------------|-------------|

【问题讨论】:

    标签: sql group-by amazon-redshift


    【解决方案1】:

    你可以试试下面的窗口函数

    select item_type, date, thresh_rchd, 
           sum(thresh_rchd) over(partition by item_type, date) as total_thresh
    from tablename
    

    【讨论】:

    • 似乎运行良好!当 group by 不削减它时,将继续使用并分区!谢谢
    【解决方案2】:
    select t1.item_type,t1.date,t1.thresh_rchd,t2.total
    from <table> t1
    inner join
    (
    select item_type,date,sum(thresh_rchd) total from <table>
    group by item_type,date) t2
    on t1.item_type=t2.item_type
    and t1.date=t2.date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-03
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多