Big Query使用count(*)返回0行

时间:2018-04-25 14:28:46

标签: sql google-bigquery

我想加入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

2 个答案:

答案 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;

这将始终返回一行,其中包含您要查找的名称数组。