【问题标题】:Group by not working as expected按未按预期工作的分组
【发布时间】:2018-05-23 22:37:35
【问题描述】:

在我的 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

我的结果显示如下

请告诉我为什么 National Calls 没有被分组。我想求国内电话和国际电话的总和

【问题讨论】:

  • 您不能在选择列表中有 customer_id 并期望它正确分组。 'National Calls' 应该显示哪个 customer_id?
  • 您是按 call_details 分组的,因此无法分辨,因为您没有显示该字段中的实际内容。
  • 所有呼叫的客户 ID 都是相同的,它不是主键。我只是想显示customer_id。让我试试没有客户密钥
  • call_details 包含 International、NSW、SA、QLD、WA。如果是国际电话,我想显示“国际电话”,否则显示“国内电话”

标签: mysql sql mysql-workbench


【解决方案1】:

使用下面的 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

【讨论】:

  • 感谢 KKK。我有更多的疑问..简单的一个;)。为什么我在尝试运行此查询时在归档列表中收到错误未知列分钟
  • 未知列表示该列在表中不存在,重新检查列名
  • 愚蠢的问题。这是拼写错误。谢谢KKK。你是明星。我得到了答案。你找到了它
  • 如果信息有用,您可以将问题标记为已回答
【解决方案2】:

您不需要子查询,因为 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;

注意:这假设您希望为每个客户提供单独的行。如果没有,请从selectgroup by 中删除customer_id

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多