来自日期表的GROUP结果与来自不同行的数据(具有相同日期)

时间:2018-06-08 09:24:03

标签: mysql

我有这张桌子,我每天都存储每个地点的访客人数:

id      datum           dag     campus      bezoekers
"1"     "2018-04-19"    "4"     "knt"       "755"
"2"     "2018-04-19"    "4"     "mar"       "238"
"3"     "2018-04-19"    "4"     "kat"       "335"
"6"     "2018-04-20"    "5"     "knt"       "736"
"7"     "2018-04-20"    "5"     "mar"       "66"
"8"     "2018-04-20"    "5"     "kat"       "327"
"9"     "2018-04-21"    "6"     "knt"       "0"
"10"    "2018-04-21"    "6"     "mar"       "0"
"11"    "2018-04-21"    "6"     "kat"       "0"

图1。

我想查询这个表,以便我得到这个结果:

DATUM       KAT     KNT     MAR
19/04/2018  335     755     238
20/04/2018  327     736     66
21/04/2018  0       0       0

图2

(因此,对于每一个日期一行,列中每个位置的访问者数量,以及位置名称作为列名称)

到目前为止,我试过这个:

SELECT
datum
,
    CASE
        WHEN campus = "knt" THEN bezoekers      
    END  AS "KNT"
,   
    CASE
        WHEN campus = "kat" THEN bezoekers  
    END  AS "KAT"
,
    CASE
        WHEN campus = "mar" THEN bezoekers
    END         AS "MAR"
FROM telling_dag 

图3

但这(逻辑上)导致:

datum           KNT     KAT     MAR
"2018-04-19"    "755"   \N      \N
"2018-04-19"    \N      \N      "238"
"2018-04-19"    \N      "335"   \N
"2018-04-20"    "736"   \N      \N
"2018-04-20"    \N      \N      "66"
"2018-04-20"    \N      "327"   \N
"2018-04-21"    "0"     \N      \N
"2018-04-21"    \N      \N      "0"
"2018-04-21"    \N      "0"     \N

图4

所以我的问题是:如何将上述结果(图4 )按日期分为1行,每个位置的3个值(如图2 < / em>的)

1 个答案:

答案 0 :(得分:1)

如果只有一个非NULL元素可以使用MAX,则必须对基准列进行分组并获得所需的结果:

SELECT
datum
,
   MAX(CASE
        WHEN campus = "knt" THEN bezoekers      
    END)  AS "KNT"
,   
    MAX(CASE
        WHEN campus = "kat" THEN bezoekers  
    END)  AS "KAT"
,
    MAX(CASE
        WHEN campus = "mar" THEN bezoekers
    END)         AS "MAR"
FROM telling_dag
GROUP BY datum