Friday, February 24, 2012

group by

I have table
date,type,price
date and price is changing
i need to group it, to have
max(date), type and price (from the row with max date)
it's no problem to take
max(date) and type bat without the third column, i need all columns
HelpUSE Northwind
GO

SET NOCOUNT ON
CREATE TABLE myTable99([date] datetime, type char(10), price money
, PRIMARY KEY (type, [date]))
GO

INSERT INTO myTable99([date],type,price)
SELECT '1/1/2001','bat' ,10.00 UNION ALL
SELECT '1/1/2002','bat' ,20.00 UNION ALL
SELECT '1/1/2003','bat' ,30.00 UNION ALL
SELECT '1/1/2004','bat' ,40.00 UNION ALL
SELECT '1/1/2001','ball',40.00 UNION ALL
SELECT '1/1/2002','ball',30.00 UNION ALL
SELECT '1/1/2003','ball',20.00 UNION ALL
SELECT '1/1/2004','ball',10.00
GO

SELECT l.*
FROM myTable99 AS l
JOIN ( SELECT type, MAX([date]) AS MAX_date
FROM myTable99
GROUP BY type) AS r
ON l.type = r.type
AND l.[date] = r.MAX_date

SET NOCOUNT OFF
DROP TABLE myTable99
GO|||Long thanks

No comments:

Post a Comment