如何获得不同列的最大值

时间:2013-04-06 19:54:58

标签: sql postgresql

我有两张这样的桌子:

LastDownloaded:

Movie    Date-last-downloaded
 A              1-1-1111
 B              2-2-2222
 C              3-3-3333
 D              4-4-4444
 E              5-5-5555

LastPurchased:

Movie    Date-last-purchased
 A              0-0-0000
 B              3-3-3333
 C              5-5-5555
 G              2-2-2222
 H              7-7-7777

我试图找到每部电影的最后下载或购买。那就是:

  • 如果同时购买和下载了电影,请返回稍后(最近的)日期
  • 否则,如果仅下载但未购买(反之亦然),请返回Date-last-downloaded(或Date-last-purchased

我该怎么办?

最终结果应该是这样的:

Movie    Date-last-purchased-or-downloaded
 A              1-1-1111
 B              3-3-3333
 C              5-5-5555
 D              4-4-4444
 E              5-5-5555
 G              2-2-2222
 H              7-7-7777

(问题名称具有误导性 - 我会很感激,如果有人会想到一个更好的并为我修复它)

2 个答案:

答案 0 :(得分:2)

select  movie
,       max(dt)
from    (
        select  Movie
        ,       Date-last-downloaded as dt
        from    LastDownloaded
        union all
        select  Movie
        ,       Date-last-purchased
        from    LastPurchased
        ) SubQueryAlias
group by
        movie

答案 1 :(得分:1)

select
    coalesce(lp.movie, ld.movie) movie,
    greatest(
        date_last_downloaded,
        date_last_purchased
    ) Date_last_purchased_or_downloaded
from
    lastdownloaded ld
    full outer join
    lastpurchased lp on ld.movie = lp.movie