我想从表中获取两个不同的值。我想获得,重复的重复数量,并希望获得总数。
WITH contrato_group AS
(
SELECT CONTRATO as u_contract, COUNT(*) AS count
FROM `table`
GROUP BY CONTRATO
)
SELECT
COUNT(DISTINCT u_contract) AS at_least_one_count
FROM
contrato_group
WHERE
count > 1
这没关系,它至少返回一个合同计数。但我也想从原始表中选择总数。
SELECT COUNT(CONTRATO) as total_contract
FROM `table`
我试过,把他们联合起来。
WITH contrato_group AS
(
SELECT CONTRATO AS u_contract, COUNT(*) AS count
FROM `table`
GROUP BY CONTRATO
)
SELECT
COUNT(DISTINCT u_contract) AS at_least_one_count
FROM
contrato_group
WHERE
count > 1
UNION ALL
SELECT
COUNT(CONTRATO) AS total_contracts
FROM
`table`
它返回了我想要的内容,但这些值只在一列中。像这样:
Row at_least_one_count
--------------------------
1 83084
2 22894
我想得到这样的结果:
Row at_least_one_count total_count
----------------------------------------
1 22894 83084
答案 0 :(得分:0)
尝试子选择
with contrato_group as (SELECT CONTRATO as u_contract, count(*) as count
FROM `table`
GROUP BY CONTRATO)
SELECT count(distinct u_contract) as at_least_one_count,
(SELECT count(CONTRATO) from `table`) as total_count
from contrato_group
WHERE count > 1
答案 1 :(得分:0)
如果您的 DBMS 支持,您也可以通过 window 函数在单个语句中执行:
select t.*
from (select distinct contrato as u_contract,
count(*) over (partition by contrato) as at_least_one_count,
count(*) over () as total_count
from table
) t
where at_least_one_count > 1;
答案 2 :(得分:0)
这样的事情怎么样。
with contrato_group as (SELECT CONTRATO as u_contract, count(*) as count
FROM test_table
GROUP BY CONTRATO)
SELECT count(case when count > 1 then 1 end) as duplicate_count,
sum(count) as total_count
from contrato_group;