简体   繁体   中英

How can I query unique columns, conditionally choosing which row based on another column's value?

I have the following setup:

date | event | hits

Jan  |   A   |  0
Jan  |   B   |  2
Jan  |   C   |  0
Feb  |   A   |  4
Feb  |   B   |  0
Feb  |   C   |  0

And I'm looking for a query that returns:

  • Events are unique (only return [Jan | B | x] or [Feb | B | x] , not both)
  • Prioritize hits (so [Jan | B | 2] beats [Feb | B | 0] )
  • Secondarily prioritize most recent date ( [Feb | C | 0] beats [Jan | C | 0] )

I would want the query for the above table to return:

Feb | A | 4
Jan | B | 2
Feb | C | 0
SELECT 
(select edate from stuff sx where s.event=sx.`Event`  ORDER BY sx.hits DESC,sx.edate DESC limit 1) date,
s.event, (select hits from stuff sx where s.event=sx.`Event`  ORDER BY sx.hits DESC,sx.edate  DESC limit 1) hits
 FROM stuff s
GROUP BY Event
order by event

Table stuff edate field is defined as date. Not very efficient for large tables, but works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM