我想加入2个表格,显示表格的一些信息以及匹配项目的总数。这是我试图在Big Query上运行的标准SQL查询:
SELECT "Active" AS type, COUNT(*) AS total, t2.display_name AS name
FROM `TABLE_1` t1
JOIN `TABLE_2` t2 ON t1.assigned_employee_id = t2.id
WHERE status = 0;
运行上面的代码给出了这个错误:
SELECT list expression references t2.display_name which is neither grouped nor aggregated at [1:69]
因此,我按照错误中的建议按display_name
进行分组,以获取以下查询:
SELECT "Active" AS type, COUNT(*) AS total, t2.display_name AS name
FROM `TABLE_1` t1
JOIN `TABLE_2` t2 ON t1.assigned_employee_id = t2.id
WHERE status = 0
GROUP BY t2.display_name
运行它给我这个输出:
Query returned zero records.
但是如果没有匹配的记录,我仍然希望返回一行,total
设置为0.如果我从原始查询中删除t2.display_name AS name
列,我将返回一行< / p>
Row | type | total
1 | Active | 0
如何获得相同的输出,但添加了dispaly_name
?
答案 0 :(得分:1)
在第二个查询中,使用条件聚合将WHERE
子句中的逻辑移动到计数中:
SELECT
"Active" AS type,
COUNT(CASE WHEN status = 0 THEN 1 END) AS total,
t2.display_name AS name
FROM `TABLE_1` t1
JOIN `TABLE_2` t2
ON t1.assigned_employee_id = t2.id
GROUP BY t2.display_name
您没有记录的一个原因是您没有任何状态为零的数据。然后,WHERE
子句将过滤掉所有记录。通过使用条件聚合,将返回每个组,计数为零,或者可能更大。
答案 1 :(得分:0)
也许你可以在一行中完成这一切?
SELECT 'Active' AS type, COUNT(*) AS total,
ARRAY_AGG(t2.display_name) AS names
FROM `TABLE_1` t1 JOIN
`TABLE_2` t2
ON t1.assigned_employee_id = t2.id
WHERE status = 0;
这将始终返回一行,其中包含您要查找的名称数组。