Dinarte Teixeira
Dinarte Teixeira

Reputation: 13

Multiple filters on SQL query

I have been reading many topics about filtering SQL queries, but none seems to apply to my case, so I'm in need of a bit of help. I have the following data on a SQL table.

Date                    item     quantity moved   quantity in stock sequence

13-03-2012 16:51:00    xpto         2                      2           1 
13-03-2012 16:51:00    xpto        -2                      0           2
21-03-2012 15:31:21    zyx          4                      6           1
21-03-2012 16:20:11    zyx          6                      12          2
22-03-2012 12:51:12    zyx         -3                      9           1

So this is quantities moved in the warehouse, and the problem is on the first two rows which was a reception and return at the same time, because I'm trying to make a query which gives me the stock at a given time of all items. I use max(date) but i don't get the right quantity on result.

Upvotes: 1

Views: 2899

Answers (3)

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115630

If you are on SQL-Server 2012, these are several nice features added.

You can use the LAST_VALUE - or the FIRST_VALUE() - function, in combination with a ROWS or RANGE window frame (see OVER clause):

SELECT DISTINCT
   item,
   LAST_VALUE(quantity_in_stock) OVER (PARTITION BY item 
                                       ORDER BY date, sequence
                                       ROWS BETWEEN UNBOUNDED PRECEDING 
                                                AND UNBOUNDED FOLLOWING) 
           AS quantity_in_stock
FROM  tableX
WHERE date <= @date_of_stock

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1270873

Add a where clause and do the summation:

select item, sum([quantity moved])
from t
group by item
where t.date <= @DESIREDDATETIME

If you put a date in for the desired datetime, remember that goes to midnight when the day starts.

Upvotes: 0

Quassnoi
Quassnoi

Reputation: 425773

SELECT  item, qty_in_stock
FROM    (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY item ORDER BY item_date DESC, sequence DESC) rn
        FROM    mytable
        WHERE   item_date <= @date_of_stock
        ) q
WHERE   rn = 1

Upvotes: 5

Related Questions