Mysql SQL:一条语句中的多个group by

Mysql SQL:一条语句中的多个group by,mysql,sql,group-by,mariadb,Mysql,Sql,Group By,Mariadb,我有这样的数据: ID NR TYPE -------------- -------------- --------------- 01 44 A 01 66 B 02 77 A 02 53 B 我需要一个查询:

我有这样的数据:

ID             NR             TYPE 
-------------- -------------- ---------------
01             44             A          
01             66             B          
02             77             A
02             53             B
我需要一个查询:

  • 按ID分组=平均编号
  • 按ID分组+类型A=平均数量A
  • 按ID分组+具有类型B=平均NR B
我认为请求应该包含一个按顺序排列的GROUPBY,但我无法使其工作


有人能帮忙吗?

使用条件聚合

select 
   id, 
   avg(case when type='A' then NR end) as 'AVG(NR A)' ,
   avg(case when type='B' then NR end) as 'AVG(NR B)',
   avg(case when type in ('A','B') then NR end) as 'AVG(NR)'
from tablename
group by id

使用条件聚合

select 
   id, 
   avg(case when type='A' then NR end) as 'AVG(NR A)' ,
   avg(case when type='B' then NR end) as 'AVG(NR B)',
   avg(case when type in ('A','B') then NR end) as 'AVG(NR)'
from tablename
group by id