Monday, March 26, 2012

Grouping Data and Selecting highest date

In SQL 2005 I have the following view:

SELECT TOP (100) PERCENT StockCode, Warehouse, QtyOnHand, QtyAllocated, QtyOnOrder, QtyOnBackOrder, DateLastSale, DateLastStockMove,
DateLastPurchase
FROM dbo.MBL_VW_AgedStock_Sales
ORDER BY StockCode

This basically shows a list of stock codes (there are multiple stock codes the same) and the last sold date. What i need to do is group the stock codes which are the same together, and show the latest date.

For example I could have the following:

STOCK CODE Last Date Sold

PC1113 11/01/2007

PC1104 15/03/2007

PC1113 15/02/2007

What I want to see is a list that shows PC1113 with its latest sold date, i.e.

STOCK CODE Last Date Sold

PC1113 15/02/2007

PC1104 15/03/2007

Any ideas?


Thanks

Kris

select StockCode, max(DateLastStockMovie) from your_table_or_view

group by stockcode

order by stockcode

|||

Something like this:

SELECT

'Stock Code' = StockCode,

'Last Sold Date' = max( DateLastSale )

FROM dbo.MBL_VW_AgedStock_Sales

GROUP BY StockCode

ORDER BY StockCode

No comments:

Post a Comment