Sql Server:如何在WHERE子句中使用像MAX这样的聚合函数

时间:2009-09-25 05:39:01

标签: sql sql-server sql-server-2005 tsql aggregate

我想获得此记录的最大值。请帮帮我:

SELECT rest.field1 
    FROM mastertable AS m
    INNER JOIN  (
        SELECT t1.field1 field1, 
               t2.field2
            FROM table1 AS T1 
            INNER JOIN table2 AS t2 ON t2.field = t1.field 
            WHERE t1.field3=MAX(t1.field3)
        --                  ^^^^^^^^^^^^^^  Help me here.
    ) AS rest ON rest.field1 = m.field

6 个答案:

答案 0 :(得分:38)

正如您所注意到的,WHERE子句不允许您在其中使用聚合。这就是HAVING条款的用途。

HAVING t1.field3=MAX(t1.field3)

答案 1 :(得分:23)

您可以使用子查询......

WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)

但实际上我会将其从where子句移出到join语句中,作为ON子句的AND。

答案 2 :(得分:7)

在having子句中使用max的正确方法是首先执行自连接:

select t1.a, t1.b, t1.c
from table1 t1
join table1 t1_max
  on t1.id = t1_max.id
group by t1.a, t1.b, t1.c
having t1.date = max(t1_max.date)

以下是如何加入子查询:

select t1.a, t1.b, t1.c
from table1 t1
where t1.date = (select max(t1_max.date)
                 from table1 t1_max
                 where t1.id = t1_max.id)

在处理多表连接时,请确保在使用聚合之前创建单个数据集:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
join #dataset d_max
  on d.id = d_max.id
having d.date = max(d_max.date)
group by a, b, c

子查询版本:

select t1.id, t1.date, t1.a, t1.b, t1.c
into #dataset
from table1 t1
join table2 t2
  on t1.id = t2.id
join table2 t3
  on t1.id = t3.id


select a, b, c
from #dataset d
where d.date = (select max(d_max.date)
                from #dataset d_max
                where d.id = d_max.id)

答案 3 :(得分:4)

SELECT rest.field1
FROM mastertable as m
INNER JOIN table1 at t1 on t1.field1 = m.field
INNER JOIN table2 at t2 on t2.field = t1.field
WHERE t1.field3 = (SELECT MAX(field3) FROM table1)

答案 4 :(得分:1)

是的,您需要在Group by子句后使用having子句, 因为只是过滤简单参数的数据, 但是group by后跟一个Having语句是将数据分组并根据某些聚合函数对其进行过滤的想法......

答案 5 :(得分:0)

但它仍然在查询生成器中给出错误消息。我正在使用SqlServerCe 2008。

SELECT         Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount, 
                     Order_Details.TotalPrice
FROM           Order_Products INNER JOIN
                     Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
                     Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING        (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))

如@powerlord所说,我用HAVING替换了WHERE。但仍然显示错误。

解析查询时出错。 [令牌行号= 1,令牌行偏移= 371,令牌错误=选择]