SELECT 列的组合出现了 COUNT 个最小条件

SELECT occurences of a combination of columns with a minimum condition on the COUNT

我每天都在 table OptionsData 中存储一些数据。在此 table 中,我对“asofdate”和“contract”两栏感兴趣。 asofdate+contract 的组合应该是唯一的:如果不是,那么我需要做一些清理工作。我想 return 3 列如下: 截至日期 !!合同 !!计数 > 1

这将使我能够识别 table 中的重复项。我尝试了以下方法:

select asofdate, contract, count(*) mycount 
from (select asofdate, contract
      from public."OptionsData"
      group by asofdate, contract
      ) AS DerivedTable
GROUP BY asofdate, contract
HAVING mycount > 1
ORDER BY mycount DESC

但这 return 是一个错误:

ERROR:  column "mycount" does not exist

如果我指定

也会发生同样的事情
HAVING DerivedTable.mycount > 1

(我也尝试了一个 WHERE 语句而不是 HAVING 但这给出了另一个错误:

ERROR:  syntax error at or near "WHERE"

)

不用说我是初学者 sql...

您不能在 GROUP BY 子句中使用别名。此外:为什么是子查询?它会将每个 asofdate 和合同的行减少到一个,因此如果您在 之后 计数,每个 asofdate / 合同对的计数为 1。

select asofdate, contract, count(*) as mycount 
from public.optionsdata
group by asofdate, contract
having count(*) > 1
order by mycount desc;