這裏是我的數據集(以哈希形式,因爲我使用的紅寶石寶石續集);哈希名稱的列名:如何將這些不同的列放入PostgreSQL的同一行?
{:item_category=>"Bacon", :year=>1890, :avg_yr_value=>0.12}
{:item_category=>"Eggs (dozen)", :year=>1890, :avg_yr_value=>0.208}
{:item_category=>"Bacon", :year=>1891, :avg_yr_value=>0.126}
{:item_category=>"Eggs (dozen)", :year=>1891, :avg_yr_value=>0.221}
{:item_category=>"Bacon", :year=>1892, :avg_yr_value=>0.129}
{:item_category=>"Eggs (dozen)", :year=>1892, :avg_yr_value=>0.221}
{:item_category=>"Bacon", :year=>1893, :avg_yr_value=>0.142}
{:item_category=>"Eggs (dozen)", :year=>1893, :avg_yr_value=>0.224}
{:item_category=>"Bacon", :year=>1894, :avg_yr_value=>0.185}
這裏是我的代碼:
SELECT
string_agg(DISTINCT item_category, ' + ' ORDER BY item_category) AS items,
year,
sum(avg_yr_value) AS amount
FROM
earnings_and_prices
WHERE
item_category = 'Bacon' OR
item_category = 'Eggs (dozen)'
GROUP BY
year
HAVING
COUNT(DISTINCT item_category) = 2
ORDER BY
year
我的結果(哈希值,因爲我使用了紅寶石的寶石續集):
{:items=>"Bacon + Eggs (dozen)", :year=>1890, :amount=>0.328}
{:items=>"Bacon + Eggs (dozen)", :year=>1891, :amount=>0.347}
{:items=>"Bacon + Eggs (dozen)", :year=>1892, :amount=>0.35}
{:items=>"Bacon + Eggs (dozen)", :year=>1893, :amount=>0.366}
我想修改自己的代碼,以便它會包括:量「培根」和:量「雞蛋(打)」,類似這樣的,例如:
{:items=>"Bacon + Eggs (dozen)", :year=>1890, :amount=>0.328, :eggs_price=>0.208, :bacon_price=>0.12}
我如何做到這一點?
意思具有每個項目的個別量到_items_輸出列,如「10×培根+ 20×蛋」? – ubik
啊,對不起。我已經添加了一個我想要的例子。 – user1626730