子查询产生了不止一个元素

subquery produced more than one element

我想获得唯一的 at_least_one 和 sql 合同的总计数。下面的代码抛出错误: 标量子查询产生了一个以上的元素

#standardSQL
WITH estrato_contrato AS (SELECT ESTRATO, CONTRATO, count(*) AS count FROM `mytable` GROUP BY ESTRATO, CONTRATO)


SELECT ESTRATO, COUNT(DISTINCT CONTRATO) AS only_once_contract, sum(count) AS total,
(SELECT COUNT(DISTINCT CONTRATO) FROM estrato_contrato WHERE count > 1 GROUP BY ESTRATO) AS at_least_one
FROM estrato_contrato
GROUP BY ESTRATO

构造子查询的正确方法是使用关联子句:

SELECT ESTRATO, COUNT(DISTINCT CONTRATO) AS only_once_contract, sum(count) AS total,
       (SELECT COUNT(DISTINCT ec2.CONTRATO)
        FROM estrato_contrato ec2
        WHERE ec2.count > 1
              ec2.ESTRATO = ec.ESTRATO
       ) AS at_least_one
FROM estrato_contrato ec
GROUP BY ESTRATO;

可能还有其他方式来编写查询,但这是您的版本的意图。

试试这个

WITH estrato_contrato AS (SELECT ESTRATO, CONTRATO, count(*) AS count FROM mytable GROUP BY ESTRATO, CONTRATO)

SELECT ESTRATO, COUNT(DISTINCT CONTRATO) AS only_once_contract, sum(count) AS total, CASE WHEN COUNT(DISTINCT CONTRATO)>1 then 1 else 0 end as at_least_one 来自 estrato_contrato 按雌激素分组

以下适用于 BigQuery 标准 SQL

选项没有子selects

#standardSQL
WITH estrato_contrato AS (
  SELECT ESTRATO, CONTRATO, COUNT(*) AS COUNT FROM  `mytable`  GROUP BY ESTRATO, CONTRATO
)
SELECT 
  ESTRATO, 
  COUNT(CONTRATO) AS only_once_contract, 
  SUM(COUNT) AS total,
  ARRAY_LENGTH(ARRAY_AGG(IF(COUNT > 1, CONTRATO, NULL) IGNORE NULLS)) AS at_least_one
FROM estrato_contrato ec
GROUP BY ESTRATO   

而且,最后最简单的一个是(注意:你不需要担心外部 select 中的不同值,因为它已经在 estrato_contrato

中得到处理
#standardSQL
WITH estrato_contrato AS (
  SELECT ESTRATO, CONTRATO, COUNT(*) AS COUNT FROM  `mytable` GROUP BY ESTRATO, CONTRATO
)
SELECT 
  ESTRATO, 
  COUNT(CONTRATO) AS only_once_contract, 
  SUM(COUNT) AS total,
  COUNTIF(COUNT > 1) AS at_least_one
FROM estrato_contrato ec
GROUP BY ESTRATO