如何在不删除重复值的情况下对数据集进行分组

时间:2019-08-09 05:14:01

标签: mysql sql

attendence sql file in here我希望对数据集进行分组而不删除重复值。

我尝试跟踪查询。我只能一次关联一天。

    SELECT 
        EnrolledID,
        Date,
        CASE WHEN Time > '1899-12-30 03:00:00' && Time <= '1899-12-30 12:15:00' THEN Time 
        END AS time_in ,
        CASE WHEN Time > '1899-12-30 12:15:00' && Time <= '1899-12-30 23:59:59' THEN Time 
        END AS time_out
    from attendance
        GROUP BY EnrolledID ;

上述查询的输出

EnrolledID      Date                time_in                 time_out    
23          2019-08-01 00:00:00     1899-12-30 07:54:40     NULL    
23          2019-08-01 00:00:00     NULL                    1899-12-30 16:01:40 
23          2019-08-02 00:00:00     1899-12-30 07:42:35      NULL   
23          2019-08-02 00:00:00    NULL                     1899-12-30 16:02:53 
23          2019-08-03 00:00:00     1899-12-30 07:37:41      NULL

预期的输出。

EnrolledID      Date                time_in                 time_out    
    23          2019-08-01 00:00:00     1899-12-30 07:54:40     1899-12-30 16:01:40 
    23          2019-08-01 00:00:00     1899-12-30 07:42:35                 1899-12-30 16:01:40 
    23          2019-08-02 00:00:00     1899-12-30 07:42:35     1899-12-31 16:15:33 
    23          2019-08-02 00:00:00     1899-12-30 07:11:51                     1899-12-30 16:02:53 
    23          2019-08-03 00:00:00     1899-12-30 07:37:41      1899-12-31 16:15:00

1 个答案:

答案 0 :(得分:0)

您可以尝试一下。由于您的查询中已经包含time intime out,因此您可以使用union all轻松获得所需的结果。

WITH CTE AS (
SELECT COUNT(Date) 
    EnrolledID,
    Date,
    CASE WHEN Time > '1899-12-30 03:00:00' && Time <= '1899-12-30 12:15:00' THEN Time 
    END AS time_in ,
    CASE WHEN Time > '1899-12-30 12:15:00' && Time <= '1899-12-30 23:59:59' THEN Time 
    END AS time_out
from attendance
    GROUP BY EnrolledID 
)
, CT AS (
    SELECT  EnrolledID, DATE, TIME_IN AS TIME FROM CTE WHERE TIME_IN IS NOT NULL 
    UNION ALL
    SELECT  EnrolledID, DATE, TIME_OUT FROM CTE WHERE TIME_OUT IS NOT NULL
)
SELECT EnrolledID, DATE , TIME FROM CTE ORDER BY DATE, TIME

如果每个日期有多个记录,而您只想要某些记录,则可以在ct部分下应用相同的过滤器,以获取所需的输出。

尽管如果您共享表架构和示例输出,那么最好提供任何建议。