【问题标题】:How can I do a group-concat call with a max value?如何进行具有最大值的 group-concat 调用?
【发布时间】:2018-12-04 11:06:40
【问题描述】:

我正在跟踪多家商店的游戏价格。我有一个games 表:

id | title       | platform_id
---|-------------|-----------
1  | Super Mario | 1
2  | Tetris      | 3
3  | Sonic       | 2

stores 表:

id | title       
---|-------------
1  | Target 
2  | Amazon      
3  | EB Games       

还有一个 copies 表,其中一个条目用于 Target 的给定游戏副本,一个条目用于 Amazon 等。我存储 SKU,以便在抓取他们的网站时使用它。

game_id | store_id | sku
--------|----------|----------
1       | 2        | AMZ-3F4YK
1       | 3        | 001481

我每天或一周或多长时间运行一次,并将结果以美分的形式存储在prices 表中:

sku       | price   | time
----------|---------|------
AMZ-3F4YK | 4010    | 13811101
001481    | 3210    | 13811105

加上一个仅将 ID 映射到名称的平台表。

这就是我感到困惑和卡住的地方。

我想发出一个查询,选择每款游戏,加上每家商店的最新价格。所以它会得到类似的结果

games.title | platform_name | info
------------|---------------|------
Super Mario | NES           | EB Games,1050;Amazon,3720;Target,5995
Tetris      | Game Boy      | EB Games,3720;Amazon,410;Target,5995

到目前为止我最好的尝试是

select
    games.title as title,
    platforms.name as platform,
    group_concat(distinct(stores.name) || "~" || prices.price) as price_info
from games
join platforms on games.platform_id = platforms.id
join copies on copies.game_id = games.id
join prices on prices.sku = copies.sku
join stores on stores.id = copies.store_id
group by title

哪个网的结果像

Super Mario | NES | EB Games~2300,Target~2300,Target~3800

也就是说,它包括列出的每个价格,而我只想要每家商店一个(并且它是最新的)。弄清楚如何整合 'select price where id = (select id from max(time)...' 等子查询来解决这个问题已经让我整晚都难过,如果有人能给我提供任何建议,我将不胜感激。

我正在使用 SQLite,但如果 Postgres 中有更好的选择,我可以在那里做。

【问题讨论】:

    标签: sql postgresql sqlite


    【解决方案1】:

    您需要两个级别的聚合。 . .而且,Postgres 对此要简单得多,所以我将使用 Postgres 语法:

    select title, platform,
           string_agg(s.name || '~' pr.price order by s.name)
    from (select distinct on (g.title, p.name, s.name) g.title as title, p.name as platform, s.name, pr.price
          from games g join
               platforms p
               on g.platform_id = p.id join
               copies c
               on c.game_id = g.id join
               prices pr
               on pr.sku = c.sku join
               stores s
               on s.id = c.store_id
          group by g.title, p.name, s.name, pr.time desc
         ) gps
    group by title, platform
    

    【讨论】:

      猜你喜欢
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多