2012-09-29 65 views
0

這裏是我的數據集(以哈希形式,因爲我使用的紅寶石寶石續集);哈希名稱的列名:如何將這些不同的列放入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} 

我如何做到這一點?

+0

意思具有每個項目的個別量到_items_輸出列,如「10×培根+ 20×蛋」? – ubik

+0

啊,對不起。我已經添加了一個我想要的例子。 – user1626730

回答

1

對於具體情況,這個查詢適合:

SELECT 
    item_bacon || ' + ' || item_eggs AS items, 
    year, 
    bacon_avg_value + eggs_avg_value AS amount, 
    bacon_avg_value AS bacon_price, 
    eggs_avg_value AS eggs_price 
FROM (
    SELECT t1.item, t2.item, t1.year, t1.avg_value, t2.avg_value 
    FROM (
      SELECT item_category, year, avg_yr_value 
      FROM earnings_and_prices 
      WHERE item_category = 'Bacon' 
    ) AS t1(item, year, avg_value) 
    JOIN (
      SELECT item_category, year, avg_yr_value 
      FROM earnings_and_prices 
      WHERE item_category = 'Eggs (dozen)' 
    ) AS t2(item, year, avg_value) 
    USING(year) 
) AS t(item_bacon, item_eggs, year, bacon_avg_value, eggs_avg_value) 
ORDER BY year 

如果您需要更多的靈活性(兩個以上的項目進行篩選和展示),我會考慮使用動態SQL查詢。

+0

是的,這有效。我在SQL新手,但我更好地理解如何做子查詢,我可以看到從子查詢如何是非常有用的。兩個簡單的問題:第2行是什麼意思?當你有類似於「t(something,something2,something3)」的東西時,這意味着什麼?你選擇包含哪些列? – user1626730

+1

@ user1626730:你需要給派生表一個別名,因此'as as t1'和'如果你說'as t(c1,c2,...)',那麼你也在命名列,如果你沒有這樣做,那麼你會得到'item_category','year'和'avg_yr_value'作爲't1'列名。''||是SQL標準的字符串連接運算符所以'item_bacon || '+' || item_eggs'就像' 「#{} item_bacon +#{} item_eggs」 '在Ruby中。 –

+0

很酷,謝謝你。 – user1626730

相關問題