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 sequel,所以这是哈希格式):

{: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 by但在 之前order by):

 having count(distinct item_category) = 2

这可确保仅包含具有两个不同 item_categories 的组。

于 2012-09-28T20:08:12.447 回答