如何在sql中通过id从组中获取名称

时间:2016-04-18 14:30:09

标签: sql group-by sum

我有一个客户群组表,我想选择群组的名称(以及另一个名为Notes的值)但是group by不允许我这样做,即使整个群组具有相同的名称和备注值

select cg.idCustomerGroup, 
       sum(case when c.type = 'child' then 1 else 0 end) as Children,
       sum(case when c.type = 'adult' then 1 else 0 end) as Adults,
       sum(case when c.type = 'senior' then 1 else 0 end) as Seniors
from CustomersGroups cg
   inner Join CustomersInGroup cig
      on cg.idCustomerGroup = cig.idCustomerGroup
   inner Join Customers c
      on c.idCustomer = cig.idCustomer
Group by cg.idCustomerGroup

1 个答案:

答案 0 :(得分:2)

您必须在GROUP BY

中加入论坛的名称和备注
select cg.idCustomerGroup, cg.Name, cg.Notes,
       sum(case when c.type = 'child' then 1 else 0 end) as Children,
       sum(case when c.type = 'adult' then 1 else 0 end) as Adults,
       sum(case when c.type = 'senior' then 1 else 0 end) as Seniors
from CustomersGroups cg
   inner Join CustomersInGroup cig
      on cg.idCustomerGroup = cig.idCustomerGroup
   inner Join Customers c
      on c.idCustomer = cig.idCustomer
Group by cg.idCustomerGroup, cg.Name, cg.Notes