在我的查询中,我有多个Case When子句,其中一个表中的数字的唯一字符串将指示输出中的唯一字符串/句子值。目前我的问题是我的Case when输出正在处理输出中的总数,但是由于第二个表中不存在第一个表中不存在的多个唯一字符串,因此应该在else语句中求和为一个总数,每个计数都在自己的行上。
我尝试在查询结束时对GROUP BY子句进行ROLLUP,但没有得到所需的预期输出。
这是我现在正在使用的东西:
SELECT
F.Identifier, F.Videogame, F.Developer,
CASE WHEN S.String='1581' THEN 'Made by billy'
WHEN S.String='1903' THEN 'Made by bob'
WHEN S.String='5849' THEN 'Made by lilly'
ELSE 'worked on by someone else' END AS Final_Name,
COUNT(distinct S.User_ID) as Count
FROM
table1 as F
JOIN
table2 as S
ON
F.Identifier=S.Identifier
GROUP BY
F.Identifier, F.Videogame, F.Developer, S.String
这是我当前得到的输出:
abcd | red dead | company1 | worked on by someone else | 1
abcd | red dead | company1 | Made by billy | 1
defg | halo 3 | company2 | Made by bob | 1
defg | halo 3 | company2 | worked on by someone else | 1
defg | halo 3 | company2 | worked on by someone else | 1
hijk | fortnite | company3 | Made by lilly | 1
这是我想要实现的输出:
abcd | red dead | company1 | worked on by someone else | 1
abcd | red dead | company1 | Made by billy | 1
defg | halo 3 | company2 | Made by bob | 1
defg | halo 3 | company2 | worked on by someone else | 2
hijk | fortnite | company3 | Made by lilly | 1
答案 0 :(得分:1)
以下是用于BigQuery标准SQL
#standardSQL
SELECT F.Identifier, F.Videogame, F.Developer,
CASE WHEN S.String='1581' THEN 'Made by billy'
WHEN S.String='1903' THEN 'Made by bob'
WHEN S.String='5849' THEN 'Made by lilly'
ELSE 'worked on by someone else' END AS Final_Name,
COUNT(DISTINCT S.User_ID) AS COUNT
FROM `project.dataset.table1` AS F
JOIN `project.dataset.table2` AS S
ON F.Identifier=S.Identifier
GROUP BY F.Identifier, F.Videogame, F.Developer, Final_Name
如您所见,唯一的解决方法是在最后一行-您需要使用S.String
来代替Final_Name
因此,如果将以上内容应用于问题中的采样数据-结果为
Row Identifier Videogame Developer Final_Name Count
1 abcd red dead company1 worked on by someone else 1
2 abcd red dead company1 Made by billy 1
3 defg halo 3 company2 Made by bob 1
4 defg halo 3 company2 worked on by someone else 2
5 hijk fortnite company3 Made by lilly 1
答案 1 :(得分:0)
这就是您需要的。
SELECT
F.Identifier, F.Videogame, F.Developer,
CASE WHEN F.String='1581' THEN 'Made by billy'
WHEN F.String='1903' THEN 'Made by bob'
WHEN F.String='5849' THEN 'Made by lilly'
ELSE 'worked on by someone else' END AS Final_Name,
S.cnt as Count
FROM
table1 as F
JOIN
(select a.Identifier, b.Developer, count(1) cnt from table2 a
join table1 b on b.Identifier = a.Identifier
Group by String, b.Developer) as S
ON
F.Identifier=S.Identifier and S.Developer = F.Developer