mysql - 使用变量时如何在查询中使用 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 服务器相对应的手册...
解决方案
不幸的是,SQL 无法像您在屏幕截图中显示的那样“合并表格单元格”。SQL 不像电子表格。
您必须获取行,然后在应用程序代码中确定您希望如何对它们进行分组。
(您在另一个线程上要求我来这里并给出答案。)
推荐阅读
- dart - 例外:类型“NativeJavaScriptObject”不是预期类型“HttpRequest”的子类型
- angular - MiniCssExtractPlugin 从应用程序全局样式 webpack 中提取 css 文件
- ruby-on-rails - 使用 Rails 5 的多种类型的帖子和类别结构
- android - 如何通过可访问性服务覆盖来制作触摸事件?
- python - Tensorflow 1.8.0:Wide and Deep Model 结果不稳定。随机种子不起作用
- enterprise-architect - DiagramObject 对象中缺少 DUID (InstanceGUID)
- html - Bootstrap3 中的弹出框 - 如何使其在内容点击时不被忽视
- vue.js - 在功能组件中,如何在渲染之前对道具进行纯粹的转换?
- c# - 如果所选日期介于预订之间,则在列表视图中显示项目
- c# - ASP.NET Core 是否支持 RESTful Web API 的 JSON Web 签名?