简体   繁体   English

如何查询唯一列,有条件地根据另一列的值选择哪一行?

[英]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) 事件是唯一的(仅返回[Jan | B | x][Feb | B | x] ,而不同时返回两者)
  • Prioritize hits (so [Jan | B | 2] beats [Feb | B | 0] ) 优先击打(因此[Jan | B | 2][Feb | B | 0]
  • Secondarily prioritize most recent date ( [Feb | C | 0] beats [Jan | C | 0] ) 其次优先处理最近的日期( [Feb | C | 0]个节拍[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. 对于大表不是很有效,但是可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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