0

这是我的数据集(哈希形式,因为我使用的是 Ruby gem Sequel);哈希名称是列名:

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

我的结果(因为我使用的是 Ruby gem Sequel,所以在哈希中):

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

我想编辑我的代码,使其包含“培根”的 :amount 和“鸡蛋(打)”的 :amount,例如:

{:items=>"Bacon + Eggs (dozen)", :year=>1890, :amount=>0.328, :eggs_price=>0.208, :bacon_price=>0.12}

我该怎么做呢?

4

1 回答 1

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 查询。

于 2012-09-29T19:49:40.190 回答