October 12, 2007 at 3:19 pm
Late on a Friday and I can't figure this one out...
I have a query that returns a derived table with values like this...
Loca Item# Total
2 931 89
3 330 910
3 933 209
3 919 100
4 931 260
4 924 89
I want to select from this derived table a single row for each location - the one with the highest total:
Loca Item# Total
2 931 89
3 330 910
4 931 260
Can't figure out the query... Thanks!
October 12, 2007 at 3:31 pm
This should get you started. You'll need to place your derived table query in place of the @DerivedTable variable in the FROM clause.
DECLARE @DerivedTable TABLE (Loca int, Item# int, Total int)
INSERT INTO @DerivedTable
SELECT 2, 931, 89 UNION ALL
SELECT 3, 330, 910 UNION ALL
SELECT 3, 933, 209 UNION ALL
SELECT 3, 919, 100 UNION ALL
SELECT 4, 931, 260 UNION ALL
SELECT 4, 924, 89
SELECT Loca, MAX(Total) as MaxTotal
FROM @DerivedTable
GROUP BY Loca
October 12, 2007 at 3:36 pm
Thanks, but I need the item# number returned also...
October 12, 2007 at 3:42 pm
This will do it, but with a derived table, you'll have to either define a temp table or table variable to hold the results, or have the derived table definition nested in your select twice.....you're call.
DECLARE @DerivedTable TABLE (Loca int, Item# int, Total int)
INSERT INTO @DerivedTable
SELECT 2, 931, 89 UNION ALL
SELECT 3, 330, 910 UNION ALL
SELECT 3, 933, 209 UNION ALL
SELECT 3, 919, 100 UNION ALL
SELECT 4, 931, 260 UNION ALL
SELECT 4, 924, 89
SELECT t1.*
FROM @DerivedTable t1
INNER JOIN (
SELECT Loca, MAX(Total) as MaxTotal
FROM @DerivedTable
GROUP BY Loca
) t2
ON t1.Loca = t2.Loca AND t1.Total = t2.MaxTotal
October 15, 2007 at 8:02 am
Thanks... used a table variable and it works great! Appreciate the help.
October 15, 2007 at 8:44 am
Be sure that the Total is unique for each location, otherwise you'll get into trouble..
Check here by adding one row as...
INSERT INTO @DerivedTable
SELECT 3, 931, 910
--Ramesh
October 15, 2007 at 8:59 am
Good point... In this case, the query that creates the @table is a summarizaton so uniqueness will be there... Thanks...
Viewing 7 posts - 1 through 6 (of 6 total)
You must be logged in to reply to this topic. Login to reply