Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL中生成键和聚合groupby函数_Sql - Fatal编程技术网

如何在SQL中生成键和聚合groupby函数

如何在SQL中生成键和聚合groupby函数,sql,Sql,我有这样的桌子 我必须像这样建造管道 ① 生成新密钥E=B或C ② 按分组键分隔每个客户 ③ 通过聚合函数groupby,如count,sum 我可以想象每一个过程,但我对合成每一个步骤感到困惑 customer group score A 1 10 B 2 20 C 1 10 B 1 10 C 2 10 D 2 10 我期望的结果是这样的 cust

我有这样的桌子

我必须像这样建造管道

① 生成新密钥
E=B或C

② 按
分组
键分隔每个客户

③ 通过聚合函数groupby,如
count
sum

我可以想象每一个过程,但我对合成每一个步骤感到困惑

customer group score
A         1     10
B         2     20
C         1     10
B         1     10
C         2     10
D         2     10

我期望的结果是这样的

customer  count(1)  count(2) avg(1) avg(2)
A           1         0        10     0
D           0         1        0      10
E           2         2        10     15
如果你有任何意见,请告诉我


感谢有条件的聚合:

select 
  case when customer in ('B', 'C') then 'E' else customer end customer,
  count(case when `group` = 1 then 1 end),
  count(case when `group` = 2 then 1 end),
  coalesce(avg(case when `group` = 1 then score end), 0),
  coalesce(avg(case when `group` = 2 then score end), 0)
from tablename
group by case when customer in ('B', 'C') then 'E' else customer end
使用双引号或方括号替换
group
周围的反勾号,以处理数据库,因为
group
是保留字。

请参见。

示例数据中没有任何内容被称为
,因此我认为示例数据与您想要完成的任务之间没有任何关系。