1

这是我的数据集(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 for Ruby。

4

2 回答 2

1

您似乎正在寻找GROUP BY聚合函数,而不是自联接:

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)可选择连接不同的名称以自动形成新标签。可以为你工作。否则用您的静态标签替换它。

于 2012-09-28T18:47:22.897 回答
1
select "Bacon and eggs", year, sum(price) 
from    table_name 
group by "Bacon and eggs", year
order by year; 
于 2012-09-28T18:47:54.180 回答