我对Google BigQuery SQL有以下疑问:
SELECT TypeOfDrink
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=1) THEN 1 ELSE 0 END) AS Sunday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=2) THEN 1 ELSE 0 END) AS Monday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=3) THEN 1 ELSE 0 END) AS Tuesday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=4) THEN 1 ELSE 0 END) AS Wednesday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=5) THEN 1 ELSE 0 END) AS Thursday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=6) THEN 1 ELSE 0 END) AS Friday,
SUM(CASE WHEN (DAYOFWEEK(CreateAt)=7) THEN 1 ELSE 0 END) AS Saturday,
COUNT(TypeOfDrink) AS AmountBought
FROM company_bigdata.Order
GROUP BY TypeOfDrink;
这很棒,但是我正在尝试将数据移植到Google Charts中,并且它需要将几周的日子作为行,并将饮料的类型作为列。但是,我目前的输出是:
Row TypeOfDrink Sunday Monday Tuesday Wednesday Thursday Friday Saturday AmountBought
1 Single Origin 5 31 12 25 11 17 0 101
2 Cappuccino 35 149 130 175 153 125 41 808
3 Caffè Mocha 24 150 161 148 176 167 6 832
但是,我希望将星期几作为行,将TypeOfDrinks作为列,如下所示:
Single Origin Cappuccino Caffe Mocha
Sunday 123 123 123 123 123
Monday 123 123 123 123 123
Tuesday
我该怎么做呢?
答案 0 :(得分:1)
SELECT
DoW,
SUM(AmountBought * (TypeOfDrink = 'Single Origin')) AS SingleOrigin,
SUM(AmountBought * (TypeOfDrink = 'Cappuccino')) AS Cappuccino,
SUM(AmountBought * (TypeOfDrink = 'Caffè Mocha')) AS CaffeMocha
FROM (
SELECT
TypeOfDrink,
CASE
WHEN (DAYOFWEEK(CreateAt)=1) THEN 'Sunday'
WHEN (DAYOFWEEK(CreateAt)=2) THEN 'Monday'
WHEN (DAYOFWEEK(CreateAt)=3) THEN 'Tuesday'
WHEN (DAYOFWEEK(CreateAt)=4) THEN 'Wednesday'
WHEN (DAYOFWEEK(CreateAt)=5) THEN 'Thursday'
WHEN (DAYOFWEEK(CreateAt)=6) THEN 'Friday'
WHEN (DAYOFWEEK(CreateAt)=7) THEN 'Saturday'
ELSE 'UnDefined'
END AS DoW,
DAYOFWEEK(CreateAt) AS pos,
COUNT(TypeOfDrink) AS AmountBought
FROM company_bigdata.Order
GROUP BY 1, 2, 3
ORDER BY pos
)
GROUP BY 1
添加了上面的紧凑版本(跳过中间分组)
SELECT
DAYOFWEEK(CreateAt) AS pos,
CASE
WHEN (DAYOFWEEK(CreateAt)=1) THEN 'Sunday'
WHEN (DAYOFWEEK(CreateAt)=2) THEN 'Monday'
WHEN (DAYOFWEEK(CreateAt)=3) THEN 'Tuesday'
WHEN (DAYOFWEEK(CreateAt)=4) THEN 'Wednesday'
WHEN (DAYOFWEEK(CreateAt)=5) THEN 'Thursday'
WHEN (DAYOFWEEK(CreateAt)=6) THEN 'Friday'
WHEN (DAYOFWEEK(CreateAt)=7) THEN 'Saturday'
ELSE 'UnDefined'
END AS DoW,
SUM(TypeOfDrink = 'Single Origin') AS SingleOrigin,
SUM(TypeOfDrink = 'Cappuccino') AS Cappuccino,
SUM(TypeOfDrink = 'Caffè Mocha') AS CaffeMocha
FROM company_bigdata.Order
GROUP BY 1, 2
ORDER BY 1