这是我的数据集(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的新手,我一直在研究自我加入方法,但它们似乎并不是我正在寻找的东西 - 我现在基本上没有想法了
如果有帮助,我也知道如何使用Sequel gem for Ruby。
答案 0 :(得分:1)
您似乎在寻找GROUP BY
和aggregate 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)
可选地连接不同的名称以自动形成新标签。可能适合你。否则用静电标签替换它。
答案 1 :(得分:1)
select "Bacon and eggs", year, sum(price)
from table_name
group by "Bacon and eggs", year
order by year;