postgresql – 使用OVER(PARTITION BY id)计数不同的值

结合窗口函数(如OVER(PARTITION BY id))可以计算不同的值吗?目前我的查询如下:
SELECT congestion.date,congestion.week_nb,congestion.id_congestion,congestion.id_element,ROW_NUMBER() OVER(
    PARTITION BY congestion.id_element
    ORDER BY congestion.date),COUNT(disTINCT congestion.week_nb) OVER(
    PARTITION BY congestion.id_element
) AS week_count
FROM congestion
WHERE congestion.date >= '2014.01.01'
AND congestion.date <= '2014.12.31'
ORDER BY id_element,date

但是,当我尝试执行查询时,我会收到以下错误

"COUNT(disTINCT": "disTINCT is not implemented for window functions"
否,正如错误消息所述,disTINCT未实现与Windows功能.从 this link到您的情况下,您可以使用以下内容
WITH uniques AS (
 SELECT congestion.id_element,COUNT(disTINCT congestion.week_nb) AS unique_references
 FROM congestion
WHERE congestion.date >= '2014.01.01'
AND congestion.date <= '2014.12.31'
 GROUP BY congestion.id_element
)

SELECT congestion.date,uniques.unique_references AS week_count
FROM congestion
JOIN uniques USING (id_element)
WHERE congestion.date >= '2014.01.01'
AND congestion.date <= '2014.12.31'
ORDER BY id_element,date

根据情况,您还可以将子查询直接放入SELECT列表中:

SELECT congestion.date,(SELECT COUNT(disTINCT dist_con.week_nb)
    FROM congestion AS dist_con
    WHERE dist_con.date >= '2014.01.01'
    AND dist_con.date <= '2014.12.31'
    AND dist_con.id_element = congestion.id_element) AS week_count
FROM congestion
WHERE congestion.date >= '2014.01.01'
AND congestion.date <= '2014.12.31'
ORDER BY id_element,date

相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...