首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >不按预期工作分组

不按预期工作分组
EN

Stack Overflow用户
提问于 2018-05-23 22:37:35
回答 2查看 562关注 0票数 2

需要帮助处理SQL查询

代码语言:javascript
运行
复制
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

我的结果显示如下

请告诉我为什么国家电话没有分组。我想找到国家电话和国际电话的总和。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-24 03:19:08

为此您不需要子查询,因为MySQL允许您在group by中使用列别名(并非所有数据库都这样做)。所以:

代码语言:javascript
运行
复制
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_idgroup by中删除group by

代码语言:javascript
运行
复制
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;

如果需要每个组中的客户ids列表,则始终可以添加group_concat(customer_id)

票数 0
EN

Stack Overflow用户

发布于 2018-05-23 22:43:13

在SQL下面使用:

代码语言:javascript
运行
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50498436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档