首页 > 解决方案 > 使用变量时如何在查询中使用 GROUP BY

问题描述

我正在使用 MySql V5.7。我有一张桌子PatientAppointment。我需要GROUP BY CDRId,它是同一张表中的一列。这是查询:

SELECT AppointmentDateTime,
       duration,
       minutes,
       @prev_month := BillingMonth BillingMonth,
       @prev_total := total total
FROM (select AppointmentDateTime,
             duration,
             @cur_dur := ((case when duration like '% hour%' then substring_index(duration, ' hour', 1) * 60 else 0 end) +
                         (case when duration like '%min%' then substring_index(substring_index(duration, ' min', 1), ' ', -1) + 0 else 0 end)) as minutes,

             CASE WHEN @year_month = date_format(AppointmentDateTime, '%Y-%m')
                  THEN @cum_sum := @cum_sum + @cur_dur
                  ELSE @cum_sum := @cur_dur
                  END total,
             @year_month := date_format(AppointmentDateTime, '%Y-%m') BillingMonth

      from PatientAppointment, (SELECT @year_month:='', @cum_sum:=0, @cur_dur:=0) variables
      GROUP BY CDRId  <------ ERROR
      ORDER BY AppointmentDateTime) subquery, 
(SELECT @prev_month:=0, @prev_total:=0) variable
ORDER BY AppointmentDateTime, total

这是一个工作db<>fiddle。 请帮我。我希望整个结果集按CDRId分组

如果我们不能在这里使用 GROUP BY 子句,我们可以在这里做一些逻辑更改。

这是我想要的分组类型。看到这个:

在此处输入图像描述

我收到此错误:

您的 SQL 语法有错误;检查与您的 MySQL 服务器相对应的手册...

标签: mysqlsqlmysql-5.7

解决方案


不幸的是,SQL 无法像您在屏幕截图中显示的那样“合并表格单元格”。SQL 不像电子表格。

您必须获取行,然后在应用程序代码中确定您希望如何对它们进行分组。

(您在另一个线程上要求我来这里并给出答案。)


推荐阅读