2

I have a problem to get the max and the min value, I want the result to be XXL and XXS

  SELECT MAX(tblSizeXL.SizeXLName) AS maxSize, 
         MIN(tblSizeXL.SizeXLName) AS minSize    
    FROM Product 
    JOIN tblSizeXL ON Product.SizeXLID = tblSizeXL.SizeXLID
   WHERE (Product.GroupID = @GroupID)
GROUP BY tblSizeXL.SizeXLID
ORDER BY tblSizeXL.SizeXLID DESC

tblSize

SizeXLID     SizeXLName
-----------------------
1            XXS
2            XS
3            S
4            M
5            L
6            XL
7            XXL
8            XXXL
OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Nicklas
  • 23
  • 1
  • 3
  • 1
    What RDBMS? Also, wouldn't the max size be XXXL? And is tblSizeXL the same as tblSize? – LittleBobbyTables - Au Revoir Sep 29 '10 at 15:16
  • Use MAX/MIN on the .SizeXLID rather than SizeXLName – D.S. Sep 29 '10 at 15:17
  • Yes its SQL-server, if I have max SizeXLID how do I get the name as result instead of the MAX number. – Nicklas Sep 29 '10 at 15:52
  • Correct XXXL is what I expect as a MAX result, sorry. – Nicklas Sep 29 '10 at 15:52
  • Are we guaranteed that SizeXLID will always order the sizes in the correct order? For example, you'd never add another row to tblSize at a later time for (9, 'XXXS')? – Joe Stefanelli Sep 29 '10 at 16:09
  • hmm maybe its better to add XXXXXXS from the begining, that dosent bother to much, thanks – Nicklas Sep 29 '10 at 16:15
  • @Nicklas, it might be better to add a size_order column to tblSizeXL and select MAX and MIN of size_order, rather than relying on the ID column always being in the correct order. That way, you can add new sizes out of sort sequence. –  Sep 29 '10 at 16:51

2 Answers2

1

You're going to have to do an inner queries to get the data you're looking for:

SELECT max.SizeXLName as maxSize, min.SizeXLName as minSize
  FROM 
  (SELECT MAX(tblSizeXL.SizeXLID) as MaxSizeXLID, MIN(tblSizeXL.SizeXLID) as MinSizeXLID
     FROM Product
     JOIN tblSizeXL ON Product.SizeXLID = tblSizeXL.SizeXLID
    WHERE Product..GroupID = @GroupID) base
  JOIN tblSizeXL max ON max.SizeXLID = base.MaxSizeXLID
  JOIN tblSizeXL min on min.SizeXLID = base.MinSizeXLID
Jeff Wight
  • 833
  • 5
  • 11
0

Remove the group by clause and your query should be fine.

CoderSivu
  • 141
  • 2
  • 7
  • Then I get this: Column "tblSizeXL.SizeXLID" is invalid in the ORDER Y clause because it is not contained in either an aggregate function or the GROUP BY clause. – Nicklas Sep 29 '10 at 15:42
  • If I understood your question, you expect the result to be a single row. In that case you don't need the 'order by' clause – CoderSivu Sep 30 '10 at 07:44