Domanda

I manage a system that records changes in it's stock item's price and quantity.

The table would look like this:

STOCK(ID, DATE, QUANTITY, PRICE)

(1, 2013.01.07 00:00, 9, 6)
(1, 2013.01.02 00:00, 9, 5)
(1, 2013.01.01 00:00, 10, 5)
(2, 2013.01.07 22:00, 20, 10)
(2, 2013.01.07 00:00, 24, 10)
(3, 2013.01.02 00:00, 9, 5)
(3, 2013.01.01 00:00, 10, 5)

The query to return changes over 1 day period should return the information for the latest history record for an item and the information for the history record that differs at most 1 day from it (or itself if there is none):

STOCK(ID, DATE_BEFORE, DATE_AFTER, QUANTITY_BEFORE, QUANTITY_AFTER, PRICE_BEFORE, PRICE_AFTER)
(1, 2013.01.07 00:00, 2013.01.07 00:00, 9, 9, 6, 6)
(2, 2013.01.07 00:00, 2013.01.07 22:00, 24, 20, 10, 10)
(3, 2013.01.01 00:00, 2013.01.02 00:00, 10, 9, 5, 5)

The query to return changes over 1 week period should return the information for the latest history record for an item and the information for the history record that differs at most 7 days from it (or itself if there is none):

STOCK(ID, DATE_BEFORE, DATE_AFTER, QUANTITY_BEFORE, QUANTITY_AFTER, PRICE_BEFORE, PRICE_AFTER)
(1, 2013.01.01 00:00, 2013.01.07 00:00, 10, 9, 5, 6)
(2, 2013.01.07 00:00, 2013.01.07 22:00, 24, 20, 10, 10)
(3, 2013.01.01 00:00, 2013.01.02 00:00, 10, 9, 5, 5)

I hope this is clear enough, as I know it's not an easy topic.

Looking forward to hearing you comments.

Thanks in advance,

H

È stato utile?

Soluzione

Disclaimer: I am not familiar with hypersonic sql dialect.

The following may help you get where you need, it seems to get what you want on mysql.

select subq.*, 
  st_before.quantity QUANTITY_BEFORE, 
  st_after.quantity QUANTITY_AFTER,  
  st_before.price PRICE_BEFORE,
  st_after.price PRICE_AFTER
from ( 
  select 
    max_id stock_id, 
    date_before,
    date_after 
  from
  (
    SELECT id max_id,max(date) date_after
    FROM STOCK
    GROUP BY ID 
  ) mx
  join 
  (  
    SELECT stock.id min_id,min(stock.date) date_before
    FROM STOCK 
    join (
       SELECT id,max(date) date_after
       FROM STOCK
       GROUP BY ID 
    ) mmx
    on stock.id = mmx.id
    and datediff(mmx.date_after, stock.date) < 1
    GROUP BY stock.ID 
  ) mn 
  on  mx.max_id = mn.min_id 
  ) subq 
  join stock st_before 
  on st_before.id = subq.stock_id 
  and st_before.date = subq.date_before 
  join stock st_after 
  on st_after.id = subq.stock_id 
  and st_after.date = subq.date_after 
  order by stock_id
;

sql fiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top