【问题标题】:GROUP_CONCAT irregardless of filterGROUP_CONCAT 不考虑过滤器
【发布时间】:2021-02-24 00:11:22
【问题描述】:

我有一个名为 attendance

的示例表
+------+--------------+--------------+-------------+--------------------+
| id   | employee_id  | date         | total_work  | is_regular_holiday |
+------+--------------+--------------+-------------+--------------------+
| 1    | e10991       |  11-01-2020  | 28800       | 1                  |
+------+--------------+--------------+-------------+--------------------+
| 2    | e10991       |  11-02-2020  | 28800       | 0                  |
+------+--------------+--------------+-------------+--------------------+
| 3    | e10992       |  11-01-2020  | 28800       | 1                  |
+------+--------------+--------------+-------------+--------------------+
| 4    | e10992       |  11-02-2020  | 28800       | 0                  |
+------+--------------+--------------+-------------+--------------------+
| 5    | e10993       |  11-02-2020  | 28800       | 0                  |
+------+--------------+--------------+-------------+--------------------+

现在我有一个问题

select 
  employee_id, 
  sum(total_work) as `total_working_hours`
from attendance
group by employee_id;

这个查询有效

现在我想得到 total_work 的所有总和(不管 is_regular_holiday = 1 与否),假期工作(如果 is_regular_holiday = 1)连接到一个字符串结果,

我尝试使用下面的查询

select 
  employee_id, 
  sum(total_work) as `total_working_hours`, 
  group_concat(select date from attendance_2 where is_holiday = 1) as holidays_worked  
from attendance
group by employee_id;

它返回一个语法错误

我在查询中遗漏了什么方法,或者可以做些什么来获得 group_concat holiday_worked?

任何帮助都会很棒!

【问题讨论】:

    标签: mysql sql string datetime aggregate-functions


    【解决方案1】:

    考虑group_concat() 中的case 表达式:

    select 
        employee_id, 
        sum(total_work) as total_working_hours, 
        group_concat(case when is_regular_holiday then date end order by date) as holidays_worked  
    from attendance
    group by employee_id;
    

    【讨论】:

    • 我有一个问题,虽然 group_concat() 是如何过滤单个日期的?是不是已经按employee_id分组了?
    • group_concat 是一个聚合函数,类似于 count 或 sum。在分组之前对每一行进行评估。
    • @Reyn:是的。 group_concat() 是一个聚合函数,它处理组中的所有行(即具有相同employee_id 的行)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 2012-10-25
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多