sql - Delete null values until first value is not null -


I have daily schedules for companies in datasets and use PostgreSQL.
For every company, all the rows with zero in column 3 will be removed for this company until the first time the tap is entered in this column. Then all the constant missing values ​​are filled with the value of the value of the last value for this company which is not faucet.

You can visualize the following example data:

  Date Company's column 3 1 2004-01-01 A5 2 2004-01-01 B null 3 2004 -01-01 c Nal 4 2004-01-02 A. Nal 5 2004-01-02 B 7 6 2004-01-02 Si Naul 7 2004-01-03 A6 8 2004-01-03 B97 2004-01 -03C910 2004-01-04 A null 11 2004-01-04 B. Noull 12 2004-01-04 Sea Null  

It would be nice if I write a query that delivers

  Date Company's column 3 1 2004-01-01 A5 2 2004-01-02 A5 3 2004-01-02 B 7 4 2004-01-03 A6 5 2004 -01-03 B 7 6 2004-01-03 C 9 7 2004-01-04 A6 8 2004-01-04 B97 2004-01-04 C 9  

I Tried:

  SELECT a.date, a.company, COALESCE (a.column3, (SELECT b.column3) is not a null order by Mercantile B WHERE b.company = a.company and b.colmun3b company = A.company DESc limit 1)) from mytable A;  

There are two problems with the code:

  1. This does not remove all records with tap values, as long as the first tap value, but / fill Has all the missing values ​​in
  2. ... not with the first observation in the column and with the last overview before the missing value.

I suggest using two subquery levels instead of correlated subqueries:

> SELECT the_date, company, max (call 3) over (alliance by company) AS to 3 (select *, count (colle 3) over (company order by the detergent) Group FRTBL) All 1, sub-2 where 3 columns are not less than zero; Company

produces the requested result.

This copy code <(code, (DDT), something should be faster for tables with more than symbols A ( exclusive ?) Index will help a lot to implement specificity:

  create index tbl_company_date_idx ON tbl (company, d_dt);  

how?

total function count () while calculating Ignoring zero values ​​is used as a composite window function, this is the default window definition of moving column Does not, which is the incompatible pricing and the current row between the and the result is being "trapped" for the rows with null values, which creates a peer group which is similar ( Non-zero) value.

In the second window function, only non-empty values ​​per group are easily extracted from maximum . Prior to the non-Rick Worl, the group retains the tap, which easily ends in the final selection.

More clarification in this closely related answer:


Comments

Popular posts from this blog

eclipse plugin - Run java code error: Workspace is closed -

ios - How do I use CFArrayRef in Swift? -

scala - Play Framework - how to bind form to a session field -