【问题标题】:MySQL: Group by and aggregate_function with conditionMySQL:按条件分组和聚合函数
【发布时间】:2016-11-23 23:17:37
【问题描述】:

我有这张桌子

  id | idDevice | type | color 
  -----------------------------
  1  |  1       | a    | red
  2  |  1       | b    | green
  3  |  1       | c    | red
  4  |  2       | a    | blue
  5  |  2       | b    | red

每个idDevice 至少有一个type 和红色color

我想为每个idDevice 获得一个type 具有color 红色(这不是唯一的),并带有这样的GROUP BY 语句:

SELECT idDevice, 
    CASE WHEN color = red THEN type END as redType 
FROM table 
GROUP BY idDevice

不幸的是,上述方法不起作用,因为即使存在红色类型,它有时也会返回 NULL redType。是否可以使用 GROUP BY 语句获得正确的 redType?

我正在寻找这个:

  idDevice | redType
  -----------------------------
    1      | a    
    2      | b    

或者这个结果:

  idDevice | redType
  -----------------------------
    1      | c    
    2      | b    

【问题讨论】:

  • 我不明白这种情况下的“或”

标签: mysql group-by aggregate-functions


【解决方案1】:

你不需要CASE,只需WHERE

SELECT idDevice, MAX(type) AS redType
FROM table
WHERE color = 'red'
GROUP BY idDevice

【讨论】:

  • 为什么要使用 max() 函数
  • 你需要使用一些东西来选择组中要选择的类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-06
  • 2011-04-11
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
  • 1970-01-01
相关资源
最近更新 更多