我想知道如何实现查询选择按clientid列分组的时间列的列WHERE子句除以月份和部门来自同一个表:
表格如下:
这里的目标是获得如下最终结果:
结果1.0
SELECT t.clientid, t.department,
(SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) FROM time_management WHERE YEAR(date)='$year' AND MONTH(date)= 12 AND department = '$department' GROUP by clientid ) as january,
(SELECT SEC_TO_TIME( SUM( TIME_TO_SEC( `time` ) ) ) FROM time_management WHERE YEAR(date)='$year' AND MONTH(date)= 2 AND department = '$department' GROUP by clientid ) as february
FROM time_management t WHERE t.department = '$department' GROUP by t.clientid
结果将以下列方式显示:
1 06:20:00 11:00:00
2 06:20:00 11:00:00
在以下情况下查询:
DB::raw
我收到错误: SQLSTATE [21000]:基数违规:1242子查询返回超过1行
由于子查询返回多行。
在子查询中没有GROUP BY,结果如下:
orderBy
所以我的问题是如何构建查询以获得结果1.0
中显示的所需结果非常欢迎任何帮助。谢谢!
答案 0 :(得分:1)
无需使用子查询。您可以使用条件聚合:
SELECT SUM( CASE WHEN MONTH(`date`) = 2 THEN TIME_TO_SEC( `time` ) ELSE 0 END) AS February,
SUM( CASE WHEN MONTH(`date`) = 12 THEN TIME_TO_SEC( `time` ) ELSE 0 END) AS December
FROM time_management
WHERE t.department = '$department'
GROUP BY clientid
这样您就可以计算一年中每个月的SUM
time
。
答案 1 :(得分:1)
尝试使用:
SELECT SUM( CASE WHEN MONTH(`date`) = 2 THEN TIME_TO_SEC( `time` ) ELSE 0 END) AS February,
SUM( CASE WHEN MONTH(`date`) = 12 THEN TIME_TO_SEC( `time` ) ELSE 0 END) AS December
FROM time_management
WHERE t.department = '$department'
GROUP BY clientid