我正在尝试编写一个查询,该查询将仅选择具有事件的行,而该行是该年中唯一的事件。
例如:
Year Event
2011 A
2011 B
2012 C
2013 B
2013 D
2014 D
Run Code Online (Sandbox Code Playgroud)
因此,我想获取行2012 C和2014 D结果。我尝试做一个GROUP BYon Year,但这不会让我选择该Event列。2011年和2013年有2个活动,因此这些不应该出现在结果中。
请帮忙。
编辑:我可以写一个嵌套查询来获取具有唯一的行count(Year) = 1用GROUP BY Year,但我无法获得Event外部查询选定列
SELECT Year, Event from table where Year in (SELECT Year from table GROUP BY Year Having count(*) = 1) as count;
Run Code Online (Sandbox Code Playgroud)
无需使用子查询或嵌套查询。您可以简单地按Year字段分组并用于HAVING COUNT(Year)=1查找所需的行。因此,适用的查询将是:
SELECT Year, Event
FROM table_name
GROUP BY Year
HAVING COUNT(Year)=1
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置找到可执行解决方案示例:
http://sqlfiddle.com/#!9/b47044/11
逻辑:
按分组时,Year将汇总同一年的所有行。因此,计数将是2对2011。
您可以通过运行以下命令进行检查:
SELECT Year, Event, COUNT(Year) as event_count
FROM table_name
GROUP BY Year
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置看到执行的中间步骤:http://sqlfiddle.com/#!9 / b47044 / 10
以上解决方案仅适用于5.7以下的MySQL版本。对于更高版本,请找到以下解决方案。
For 5.7 and greater the ONLY_FULL_GROUP_BY SQL mode is enabled by default so this will fail. Either you can update this mode( Refer answers under SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by ) or alternatively you can use ANY_VALUE() function to refer to the non-aggregated column, so update query that will work in MySQL 5.7 and greater is:
SELECT Year, ANY_VALUE(Event)
FROM table_name
GROUP BY Year
HAVING COUNT(Year)=1;
Run Code Online (Sandbox Code Playgroud)
You can find executable example at: https://paiza.io/projects/e/tU-7cUoy3hQUk2A7tFfVJg
Reference: https://docs.oracle.com/cd/E17952_01/mysql-5.7-en/miscellaneous-functions.html#function_any-value
| 归档时间: |
|
| 查看次数: |
343 次 |
| 最近记录: |