按未按预期工作分组

ktecyv1j  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(594)

需要我的sql查询帮助吗

Query : 

Select customer_id,
       if (call_details ='International' , 'International Calls', 'National Calls'),
       sum(minutes) 
from call_minutes 
where date between '$from' and '$to' 
group by call_details

我的结果显示如下

请让我知道为什么全国电话不分组。我想找出国内电话和国际电话的总和

a6b3iqyw

a6b3iqyw1#

这不需要子查询,因为mysql允许在 group by (并非所有数据库都这样做)。所以:

Select customer_id,
       (case when call_details = 'International'
             then 'International Calls'
             else 'National Calls'
        end) as call_group,
       sum(minutes) 
from call_minutes 
where date between '$from' and '$to' 
group by customer_id, call_group;

注意:这假设您希望每个客户都有单独的行。如果没有,请移除 customer_id 从两个 select 以及 group by :

Select (case when call_details = 'International'
             then 'International Calls'
             else 'National Calls'
        end) as call_group,
       sum(minutes) 
from call_minutes 
where date between '$from' and '$to' 
group by call_group;

如果您想要每个组中的客户id列表,您可以随时添加 group_concat(customer_id) .

yh2wf1be

yh2wf1be2#

使用以下sql:

select customer_id,
       call_details,
       sum(minutes) as minutes
from(
Select customer_id,
       if (call_details ='International' , 'International Calls', 'National Calls') as call_details,
       minutes
from call_minutes 
where date between '$from' and '$to') x 
group by customer_id,call_details

相关问题