Using max and group by twice

自闭症网瘾萝莉.ら 提交于 2019-12-25 01:45:20

问题


I read some articles on this topic including: Use of GROUP BY twice in MySQL and know this should be the same logic I need but I just don’t know how to apply it.

Please note that I know the schema is terrible (I still don’t understand why the edition and published tables are separate for example….) but I don’t have any power to change it.

(I have some sensitive information that I am working with so I will model my problem using an example using movies instead.)

Tables:

Title
TitleID     MovieTitle
1           Great Movie #1
2           Great Movie #2

Edition
StockNo editionID   EditionText         Media       TitleID
1           1       Regular Edition     DVD         1
2           1       Regular Edition     Blue-ray    1
3           2       Extended Version    DVD         1
4           2       Extended Version    Blue-ray    1
5           1       Regular Edition     DVD         2
6           1       Regular Edition     Blue-ray    2
7           2       Extended Version    DVD         2
8           2       Extended Version    Blue-ray    2

Published
StockNo DatePublished
1       1999.01.01
2       2003.01.01
3       2000.01.01
4       1999.01.01
5       1997.01.01
6       1998.01.01
7       2012.01.01
8       2009.01.01

I want to return rows with each row being an edition of one of the titles. For each edition of the title I want to return the latest published date, regardless of the media.

E.g.:

Great move #1, Regular version, Latest_published_date

Great movie #1, Extended version, Latest_published_date

Great move #2, regular version, Latest_published_date

Great movie #2, extended version, Latest_published_date

I’m just lost in a sea of logic….

WITH Datespublished AS
(   Select  tt.titleid
            ,ed.editionID
            ,pb.datepublished 
    FROM    title tt
            left join edition ed on tt.titleid=ed.titleid
            left join published pb on pb.stockno=ed.stockno
)


select titleid, editionID, max (datepublished) as maxdate from Datespublished group by titleid THEN editionID?!?!?!?

回答1:


You can group by on multiple columns by separating them with a comma. Change:

group by titleid THEN editionID

to:

group by titleid, editionID



回答2:


What you need are the window functions, in particular, the one for max(). The following gets you the max published date for each edition:

Select  tt.titleid, ed.editionID, pb.datepublished,
        max(datepublished) over (partition by e.editionId) as EditionPublished
FROM    title tt  left join
        edition ed
        on tt.titleid=ed.titleid left join
        published pb
        on pb.stockno=ed.stockno;


来源:https://stackoverflow.com/questions/18060163/using-max-and-group-by-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!