29

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

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
4

6 回答 6

42

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

HAVING t1.field3=MAX(t1.field3)
于 2009-09-25T15:34:56.623 回答
31

您可以使用子查询...

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

但我实际上会将它从 where 子句中移出并放入 join 语句中,作为 ON 子句的 AND。

于 2009-09-25T05:43:51.263 回答
9

在 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)
于 2013-07-17T21:07:13.167 回答
5
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)
于 2009-09-25T06:02:31.620 回答
1

是的,您需要在 Group by 子句之后使用 having 子句,因为 where 只是过滤简单参数上的数据,但是 group by 后跟 Have 语句是对数据进行分组并根据某些聚合进行过滤的想法功能......

于 2012-03-26T16:35:15.833 回答
1

但它仍然在查询生成器中给出错误消息。我正在使用 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。但仍然显示错误。

解析查询时出错。[Token line number = 1, Token line offset = 371, Token in error = SELECT]

于 2013-11-07T04:39:00.117 回答