子查询产生了多个元素

时间:2018-05-31 13:11:00

标签: sql google-bigquery standard-sql

我希望获得与sql签订合同的唯一,at_least_one和总计数。下面的代码抛出一个错误: 标量子查询产生了多个元素

#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

3 个答案:

答案 0 :(得分:2)

制定子查询的正确方法是使用关联子句:

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;

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

答案 1 :(得分:0)

试试这个

WITH estrato_contrato AS(SELECT ESTRATO,CONTRATO,count(*)AS count FROM EStable 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 as_least_one 来自estrato_contrato GROUP BY ESTRATO

答案 2 :(得分:0)

以下是BigQuery Standard SQL

没有子选择的选项

#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   

最后,最简单的是(注意:你不必担心外部选择中的不同值,因为它已经在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