【问题标题】:How do I find the sum of two categories for each year in this PostgreSQL dataset?如何在这个 PostgreSQL 数据集中找到每年两个类别的总和?
【发布时间】:2012-09-28 18:36:30
【问题描述】:

这是我的数据集(CSV 格式,便于阅读):

item_category,year,price
"Bacon",1890,0.12
"Bacon",1891,0.126
"Bacon",1892,0.129
"Bacon",1893,0.142
"Eggs (dozen)",1890,0.208
"Eggs (dozen)",1891,0.221
"Eggs (dozen)",1892,0.221
"Eggs (dozen)",1893,0.224

我想找出每年培根和鸡蛋的价格总和。所以,我想要的结果是:

item_category,year,price
"Bacon and eggs",1890,0.328
"Bacon and eggs",1891,0.347
"Bacon and eggs",1892,0.35
"Bacon and eggs",1893,0.366

我是 SQL 的新手,我一直在研究 Self-Join 方法,但它们似乎并不是我想要的——我现在基本上已经没有想法了.

如果有帮助,我还知道如何将 Sequel gem 用于 Ruby。

【问题讨论】:

    标签: ruby postgresql sequel


    【解决方案1】:

    您似乎在寻找GROUP BYaggregate functions,而不是自加入:

    SELECT string_agg(DISTINCT item_category, ' and ' ORDER BY item_category)
                                                                       AS items
         , year
         , sum(price) AS price
    FROM   tbl
    GROUP  BY year
    ORDER  BY year
    

    string_agg(DISTINCT item_category, ' and ' ORDER BY item_category) 可以选择连接不同的名称以自动形成新标签。可以为你工作。否则将其替换为您的静态标签。

    【讨论】:

      【解决方案2】:
      select "Bacon and eggs", year, sum(price) 
      from    table_name 
      group by "Bacon and eggs", year
      order by year; 
      

      【讨论】:

      • GROUP BY 中删除“培根和鸡蛋”。无需按标量值分组。此外,它必须是单引号 'Bacon and eggs',而不是双引号,因为这是一个字符串值,而不是标识符。 IOW:这根本行不通。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2018-08-29
      相关资源
      最近更新 更多