views:

45

answers:

1

I have a table some thing like as follows for Inventory details.

InventoryTable.

InventoryTableID  DateCreated  quantity  ItemName
-------------------------------------------------
1                 2010-02-04   12        abc
2                 2010-03-10   4         abc
3                 2010-03-13   5         xyz
4                 2010-03-13   19        def
5                 2010-03-17   15        abc
6                 2010-03-29   15        abc
7                 2010-04-01   22        xyz
8                 2010-04-13   5         abc
9                 2010-04-15   6         def    

from the above table if my admin wants to know the inventory details for month April 2010 (i.e. Apr 1st 2010 - Apr 30th 2010)

I need the output as shown below.

  1. inventory as on Apr 1st 2010

    ItemName  Datecreated   qty
    ----------------------------
    abc       2010-03-29    15
    xyz       2010-04-01    22
    def       2010-03-13    19
    
  2. inventory as on Apr 30th 2010

    ItemName  Datecreated  qty
    ---------------------------
    abc       2010-04-13   5
    xyz       2010-04-01   22
    def       2010-04-15   6
    
+3  A: 

For your first result set, run with @YourDataParam = '2010-04-01'. For the second set, use '2010-04-30'.

;with cteMaxDate as (
    select it.ItemName, max(it.DateCreated) as MaxDate
        from InventoryTable it
        where it.DateCreated <= @YourDataParam
        group by it.ItemName
)
select it.ItemName, it.DateCreated, it.qty
    from cteMaxDate c
        inner join InventoryTable it
            on c.ItemName = it.ItemName
                and c.MaxDate = it.DateCreated
Joe Stefanelli
+1 For understanding the question ;-).
Vash
Excellent it worked for me.
desi
Thanks so much Joe Stefanelli. The logic worked fantastic
desi