问题描述
我每天都会在表OptionsData中存储一些数据。在此表中,我对两列“ asofdate”和“ contract”感兴趣。 asofdate + contract的组合应该是唯一的:如果不是,那么我需要进行一些清理。我想返回3列,如下所示: 截至日期 !!合同!数> 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的初学者...
解决方法
您不能在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;