在PostgreSQL中获取总和时,如何跳过包含null(或nil)值的行?

时间:2012-09-28 20:02:53

标签: ruby postgresql sequel

我的数据集:

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续集,所以这是Hash格式):

{: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}

我只想要包含培根和面包价格的年份。我该怎么做?

1 个答案:

答案 0 :(得分:1)

将以下内容添加到您的查询中(在group by之后但在order by之前):

 having count(distinct item_category) = 2

确保只包含具有两个不同item_categories的组。