1

私のデータセット:

item_category,year,price
"Bacon",1910,0.255
"Bacon",1911,0.247
"Bacon",1912,0.244
"Bacon",1913,0.27
"Bread",1913,0.056
"Bread",1914,0.063
"Bread",1915,0.07
"Bread",1916,0.073

これまでの私のコード:

SELECT
    string_agg(DISTINCT item_category, ' and ' ORDER BY item_category) AS items,
        year,
        sum(avg_yr_value) AS price
FROM
    earnings_and_prices
WHERE
    (item_category = 'Bacon' OR item_category = 'Bread')
GROUP BY
    year
ORDER BY
    year

私の出力(私はRuby gemの続編を使用しているので、これはハッシュ形式です):

{:items=>"Bacon", :year=>1910, :price=>0.255}
{:items=>"Bacon", :year=>1911, :price=>0.247}
{:items=>"Bacon", :year=>1912, :price=>0.244}
{:items=>"Bacon and Bread", :year=>1913, :price=>0.326}
{:items=>"Bacon and Bread", :year=>1914, :price=>0.338}
{:items=>"Bacon and Bread", :year=>1915, :price=>0.339}
{:items=>"Bacon and Bread", :year=>1916, :price=>1.017}

ベーコンとパンの両方の価格が含まれている年だけが欲しいです。どうすればよいですか?

4

1 に答える 1

1

クエリに以下を追加します(後、group byorder by):

 having count(distinct item_category) = 2

これにより、2つの異なるitem_categoriesを持つグループのみが含まれるようになります。

于 2012-09-28T20:08:12.447 に答える