0
我试图创建基于表格的视图。我想获得一组现有的tax_id_no
行,每行都有最新的信息。所以我按时间戳降序排列。但是,每个tax_id_no
可以有多行,并不是每行都会有所有的信息。所以我想为每一列获得第一个有效的信息。现在我得到了这个:为PostgreSQL中的多列和不同行选择第一个非空值
SELECT * FROM
(
SELECT DISTINCT ON (store_id, tax_id_no)
event_id,
event_tstamp,
owner_id,
store_id,
tax_id_no,
first_value(year_built) OVER (ORDER BY year_built IS NULL, event_tstamp) AS year_built, --New
first_value(roof_replaced_year) OVER (ORDER BY roof_replaced_year IS NULL, event_tstamp) AS roof_replaced_year, --New
first_value(number_of_rooms) OVER (ORDER BY number_of_rooms IS NULL, event_tstamp) AS number_of_rooms, --New
FROM MySchema.Event
WHERE tax_id_no IS NOT NULL AND tax_id_no != ''
order by store_id, tax_id_no, event_tstamp DESC
) t1
WHERE owner_id IS NOT NULL OR owner_id != '';
虽然这是获得每行相同的第一个有效信息。因此,与其让这样的结果,这就是我想要的:
event_id event_tstamp owner_id store_id tax_id_no year_built roof_replaced_year number_of_rooms
04 2016-05-12 123 02 12345 1996 2009 6
05 2017-02-02 245 02 23456 1970 1999 8
08 2017-03-03 578 03 34567 2002 2016 10
我得到这个,这都在寻找相同的first_value
列行:
event_id event_tstamp owner_id store_id tax_id_no year_built roof_replaced_year number_of_rooms
04 2016-05-12 123 02 12345 1996 2009 6
05 2017-02-02 245 02 23456 1996 2009 6
08 2017-03-03 578 03 34567 1996 2009 6
是否有可能为每一行选择不同的first_value
?我想我可以在同一张表中做多种选择的连接,但我不确定这会实际给我每行的唯一值,而不是再次遇到同样的问题。此类查询的时间也很长,到目前为止,这些查询的代价非常昂贵。
通过在窗函数的'顺序by'表达的前立即tax_id_no'添加'分区。 – systemjack
@systemjack谢谢,这工作。如果你将它作为答案发布,我会接受它。 –