给出表中的以下数据:
RIDER_ID, DEST1, DEST2, DEST3
'864', '387', '24', NULL
'864', '24', '1', NULL
'864', '732', '1', NULL
以及以下语句:
SELECT DISTINCT(RIDER_ID), DEST1, DEST2, DEST3,
(CASE WHEN START_DATE BETWEEN '2018-11-01 00:00:00' AND ' 2018-11-01 23:59:59 ' THEN COUNT(DEST1) + COUNT( DEST2) + COUNT(DEST3) END) AS '2018-11-01',
(CASE WHEN START_DATE BETWEEN '2018-11-02 00:00:00' AND ' 2018-11-02 23:59:59 ' THEN COUNT(DEST1) + COUNT( DEST2) + COUNT(DEST3) END) AS '2018-11-02'
FROM SCHEDULE
WHERE START_DATE BETWEEN '2018-11-01 00:00:00' AND '2018-11-02 23:59:59' AND RIDER_ID = 864
GROUP BY START_DATE, RIDER_ID, DEST1, DEST2, DEST3
结果如下:
RIDER_ID, 2018-11-01, 2018-11-02
'864', '2', NULL
'864', '2', NULL
'864', NULL, '2'
但是,我想要的是:
RIDER_ID, 2018-11-01, 2018-11-02
'864', '4', '2'
因此,RIDER 864在第一个日期共有4个目的地,在第二个日期共有2个目的地。当然,每个月的每一天和每个RIDER_ID都有列。
换句话说,每个RIDER_ID仅包含一条记录,其中日期列包含目的地的总计数。字段中的值是索引值,在这里无关紧要。只需计算是否有一个值(表示每个RIDER_ID和DATES的总目的地)即可。
到目前为止,我还无法提出正确的陈述。啊
答案 0 :(得分:0)
如果只从字段列表和group by子句中删除DEST1,DEST2,DEST3,我想您应该会得到想要的东西。
distinct(RIDER_ID)无效,因为您已经按该字段分组了。
但是,即使结构稍有不同,您也可能会得到类似的结果:
SELECT RIDER_ID, DATE(START_DATE) AS DATE_START,
COUNT(DEST1) + COUNT( DEST2) + COUNT(DEST3) AS RIDES
FROM SCHEDULE
WHERE START_DATE BETWEEN '2018-11-01 00:00:00'
AND '2018-11-02 23:59:59' AND RIDER_ID = 864
GROUP BY RIDER_ID, DATE_START;
这应该以以下格式返回您的数据:
RIDER_ID, DATE_START, RIDES
'864', '2018-11-01', 4
'864', '2018-11-02', 2
答案 1 :(得分:0)
使用条件聚合,通常需要条件 inside 聚合函数,如下所示:
SELECT RIDER_ID
, SUM(CASE WHEN START_DATE BETWEEN '2018-11-01 00:00:00' AND ' 2018-11-01 23:59:59 '
THEN IF(DEST1 IS NULL,0,1) + IF(DEST2 IS NULL,0,1) + IF(DEST3 IS NULL,0,1)
END) AS `2018-11-01`
, SUM(CASE WHEN START_DATE BETWEEN '2018-11-02 00:00:00' AND ' 2018-11-02 23:59:59 '
THEN IF(DEST1 IS NULL,0,1) + IF(DEST2 IS NULL,0,1) + IF(DEST3 IS NULL,0,1)
END) AS `2018-11-02`
FROM SCHEDULE
WHERE START_DATE BETWEEN '2018-11-01 00:00:00' AND '2018-11-02 23:59:59'
AND RIDER_ID = 864
GROUP BY RIDER_ID
;
此外,在编写此文件时,我注意到SUM可能更适合您想要的内容。
旁注:CASE
比IF()
具有更高的可移植性,并且可以嵌套。在示例中,我使用IF来提高清晰度。