Question

I have two tables

Product table
productid   int
productname varchar(32)

and

productprice table
productid    int
effectiviedt date
inactivedt   date
price        decimal (10,2)

i have a bunch of records some products has duplicate effectivedt what i want to do is for each record find the duplicate effectivedt and only keep the longest running one the inactivedt is also a date so the length would be form the effectivedt to the inactivedt

i have been trying to do it for a while but have had no luck what so ever.

i started with try to find at the earliest dates but realised that doesn't work becuase the duplicates may not be earliest dates

i cant find a way to get the difference between effectivedt and inactivedt as i cant have it in the where or having or on clause

so ye i been trying for a good long whi,e no to no avail any help would make me cry with thankfullness

thanks you in advance

No correct solution

OTHER TIPS

You can calculate the date difference in teh SELECT statement like this:

SELECT ..., DATEDIFF(effectivedt, inactivedt) as active_length, ...

You can then use the result in WHERE, ORDER BY, etc.

Simple delete with exactly the same startdate, but the one that is deleted having an earlier stopdate.

DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE productprice
        ( id INTEGER NOT NULL
        , startdate date
        , stopdate date
        , price        decimal (10,2)
        );

INSERT INTO productprice(id,startdate,stopdate,price) VALUES
 ( 1, '2012-07-01', '2012-07-10', 10.0 )
,( 1, '2012-07-01', '2012-07-01', 20.0 )
,( 2, '2012-07-05', '2012-07-06', 30.0 )
,( 2, '2012-07-05', '2012-07-10', 40.0 )
        ;

DELETE FROM productprice de
WHERE EXISTS ( SELECT *
        FROM productprice ex
        WHERE ex.id=de.id
        AND ex.startdate = de.startdate
        AND ex.stopdate > de.stopdate
        )
        ;

SELECT * FROM productprice;

Result:

CREATE TABLE
INSERT 0 4
DELETE 2
 id | startdate  |  stopdate  | price 
----+------------+------------+-------
  1 | 2012-07-01 | 2012-07-10 | 10.00
  2 | 2012-07-05 | 2012-07-10 | 40.00

Thank you that works very well more or less exactly what i want, the only problem is i only want to keep one record is two are the same for example so if i have

2012-07-05 | 2012-07-10 
2012-07-07 | 2012-07-25 
2012-07-07 | 2012-07-27
2012-07-27 | 2012-07-32

it should keep only one of the 2012-07-07 | 2012-07-27

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top