为什么我使用case语句在第二个计数器中得到Null值

时间:2017-07-14 07:37:25

标签: mysql sql

第一个案例陈述我得到了正确的结果,但在第二个案例中 为什么我得到一个NULL结果我的第二个case语句counter = 2 这是我有一个图像的结果 Query Result that i got Null data in second statement when i grouped by on my date

SELECT DISTINCT date,log,

              CASE
                WHEN note = 'HOLIDAY' AND counter = 1
                THEN 'HOLIDAY'
              END note1,

              CASE
                WHEN note = 'HOLIDAY' AND counter = 2
                THEN 'HOLIDAY'
              END note2,

    FROM  timesheet 
    WHERE timesheet.empid='40' AND date <= CURDATE() AND YEAR(date)= YEAR(CURDATE())
        AND MONTH(date) = MONTH(CURDATE()) 
    GROUP BY date 
    ORDER BY date DESC;

1 个答案:

答案 0 :(得分:0)

您使用GROUP BY错误。规则是SELECT子句中的每一列都在GROUP BY子句中,或者必须对其应用聚合函数(如count,min,max,avg)。

如果您不遵守此规则,则会显示每个组的随机行。在您的情况下,当您确实拥有note = 'HOLIDAY' AND counter = 2的数据时,该组的行可能如下所示

NULL
HOLIDAY
NULL
NULL

但是在折叠之后(当选择输出它时),只显示第一行,因此为NULL值。

试试这样:

SELECT date,
MIN(log), /*or maybe you want to group by this column, too? */

              MAX(CASE
                WHEN note = 'HOLIDAY' AND counter = 1
                THEN 'HOLIDAY'
              END) note1,

              MAX(CASE
                WHEN note = 'HOLIDAY' AND counter = 2
                THEN 'HOLIDAY'
              END) note2,

    FROM  timesheet 
    WHERE timesheet.empid='40' AND date <= CURDATE() AND YEAR(date)= YEAR(CURDATE())
        AND MONTH(date) = MONTH(CURDATE()) 
    GROUP BY date 
    ORDER BY date DESC;

另请注意,我删除了DISTINCT。您的GROUP BY已经这样做了。