我的问题是,他们不能按我的需要工作.我可以使用一个postgresql向导的帮助.我正在使用postgresql 9.2 – 以防该版本提供解决方案easyyer.
询问
select v.ID,v.active,v.reg_no,p.install_date,p.remove_date from vehicle v left join period p on (v.ID = p.car_ID) where v.ID = 1 order by v.ID,p.install_date asc
返回6行:
ID,active,reg_no,install_date,remove_date1,TRUE,something,2008-08-02 11:13:39,2009-02-09 10:32:32....1,2010-08-15 21:16:40,2012-08-25 07:44:301,2012-09-10 17:05:12,NulL
但是当我使用聚合查询时:
select max(ID) as ID,last(active) as active,first(install_date) as install_date,last(remove_date) as remove_date from ( select v.ID,p.remove_date from vehicle v left join period p on (v.ID = p.car_ID) where v.ID = 1 order by v.ID,p.install_date asc) as bar group by ID
然后我明白了
ID,2012-08-25 07:44:30
不
ID,NulL
正如我所料
如果最后一行的值为null,而不是最后一个现有值,是否可以以某种方式更改聚合函数以产生NulL?
EDIT1
Roman Pekar提出alternative solution我的问题,但这不符合我的需要.原因是 – 我简化了原始查询.但我运行的查询更复杂.我意识到可能有我的问题的替代解决方案 – 这就是为什么更新帖子以包括原始的,更复杂的查询.这是:
select partner_ID,sum(active) as active,sum(installed) as installed,sum(removed) as removed from ( select pc.partner_ID as partner_ID,v.ID,CASE WHEN v.active = TRUE THEN 1 ELSE 0 END as active,CASE WHEN first(p.install_date) BETWEEN '2013-12-01' AND '2014-01-01' THEN 1 ELSE 0 END as installed,CASE WHEN last(p.remove_date) BETWEEN '2013-12-01' AND '2014-01-01' THEN 1 ELSE 0 END as removed from vehicle v left join period p on (v.ID = p.car_ID) left join partner_clIEnts pc on (pc.account_ID = v.clIEnt_ID) group by pc.partner_ID,v.active) as foo group by partner_ID
正如您所看到的,我实际上需要获得几辆车的第一个和最后一个值而不是一个,并最终汇总这些车辆的所有者的车辆数量.
/ EDIT1
解决方法 您可以使用窗口函数lead()
and lag()
来检查第一个和最后一个记录,例如: select max(a.ID) as ID,max(a.first) as first,max(a.last) as lastfrom ( select v.ID,case when lag(v.ID) over(order by v.ID,p.install_date) is null then p.install_date end as first,case when lead(v.ID) over(order by v.ID,p.install_date) is null then p.remove_date end as last from vehicle v left join period p on (v.ID = p.car_ID) where v.ID = 1 ) as a
sql fiddle demo
总结以上是内存溢出为你收集整理的postgresql中的第一个和最后一个值聚合函数,它们可以正确地使用NULL值全部内容,希望文章能够帮你解决postgresql中的第一个和最后一个值聚合函数,它们可以正确地使用NULL值所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)