简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM