admin

SELECT在COUNT个条件最少的列组合中出现

sql

我每天都会在表OptionsData中存储一些数据。在此表中,我对两列“ asofdate”和“ contract”感兴趣。asofdate +
contract的组合应该是唯一的:如果不是,那么我需要进行一些清理。我想返回3列,如下所示:asofdate !! 合同 !!计数> 1

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

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

但这返回一个错误:

ERROR:  column "mycount" does not exist

如果我指定,也会发生同样的事情

HAVING DerivedTable.mycount > 1

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

ERROR:  syntax error at or near "WHERE"

不用说我是sql的初学者…


阅读 187

收藏
2021-07-01

共1个答案

admin

您不能在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;
2021-07-01