SQL MAX和MIN在一列中

时间:2010-09-29 15:11:22

标签: sql sql-server tsql aggregate-functions

我有一个问题是得到最大值和最小值,我希望结果是XXL和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

2 个答案:

答案 0 :(得分:1)

您将不得不进行内部查询以获取您正在寻找的数据:

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

答案 1 :(得分:0)

删除group by子句,您的查询应该没问题。