结合窗口函数(如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到您的情况下,您可以使用以下内容:
原文链接:https://www.f2er.com/postgresql/191782.htmlWITH 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