我们说我有查询
#standardSQL
SELECT a.person, score, dte
FROM
(
SELECT 'Aaron' person UNION ALL
SELECT 'Baron' person UNION ALL
SELECT 'Cindy' person
)a
LEFT JOIN
(
SELECT 'Aaron' person, 10 score, 20 dte UNION ALL
SELECT 'Baron' person, 20 score, 20 dte UNION ALL
SELECT 'Aaron' person, 10 score, 21 dte UNION ALL
SELECT 'Cindy' person, 10 score, 21 dte UNION ALL
SELECT 'Baron' person, 20 score, 21 dte
)b
on a.person = b.person
order by dte
结果是
Row person score dte
1 Aaron 10 20
2 Baron 20 20
3 Aaron 10 21
4 Baron 20 21
5 Cindy 10 21
现在,我是否还可以获得" Cindy"得分为0而dte = 20?
所以期望是:
Row person score dte
1 Aaron 10 20
2 Baron 20 20
3 Cindy 0 20
4 Aaron 10 21
5 Baron 20 21
6 Cindy 10 21
使用左连接并不是必需的。基本上,我只有1个表,但只想为每个dte和person拥有0的数据。
答案 0 :(得分:2)
以下是BigQuery Standard SQL
#standardSQL
WITH persons AS (
SELECT 'Aaron' person UNION ALL
SELECT 'Baron' person UNION ALL
SELECT 'Cindy' person UNION ALL
SELECT 'Mike' person
), scores AS (
SELECT 'Aaron' person, 10 score, 20 dte UNION ALL
SELECT 'Baron' person, 20 score, 20 dte UNION ALL
SELECT 'Aaron' person, 10 score, 21 dte UNION ALL
SELECT 'Cindy' person, 10 score, 21 dte UNION ALL
SELECT 'Baron' person, 20 score, 21 dte
), dtes AS (
SELECT DISTINCT dte
FROM scores
)
SELECT a.person, IFNULL(score, 0) score, d.dte
FROM persons a CROSS JOIN dtes d
LEFT JOIN scores b
ON a.person = b.person AND d.dte = b.dte
ORDER BY dte, person
结果如下
person score dte
Aaron 10 20
Baron 20 20
Cindy 0 20
Mike 0 20
Aaron 10 21
Baron 20 21
Cindy 10 21
Mike 0 21