SQL查询,使用MAX()代替TOP

时间:2018-06-19 12:57:51

标签: sql

我必须从Common_CustomerComments表中获取一个描述,该描述具有最大优先级(最大优先级为3)和最大InsertDate

我使用了此查询

select TOP 1 Description 
from Common_CustomerComments 
WHERE CustomerCode = 1 
  AND Priority > 1 
ORDER BY Priority desc, InsertDate desc

但是我需要创建不带“ TOP”的查询,有人可以帮助我使用MAX()函数创建查询

我尝试了此查询,但是对此有疑问:

SELECT Description 
FROM Common_CustomerComments 
WHERE CustomerCode = 1 
  and Id IN (SELECT MAX(Priority) 
             FROM Common_CustomerComments pr 
             JOIN (SELECT MAX(InsertDate) as maxdata))

2 个答案:

答案 0 :(得分:0)

我会使用ROW_NUMBER()

select cc.Description 
from (select cc.*,
             row_number() over (partition by customercode order by priority desc, insertdate desc) as seqnum
      from Common_CustomerComments
      where CustomerCode = 1 and Priority > 1  
     ) cc
where seqnum = 1;

答案 1 :(得分:0)

通用中,您可以将subquery correlation 方法结合使用:

select cc.*
from Common_CustomerComments cc
where id = (select top 1 cc1.id
            from Common_CustomerComments cc1
            where cc1.customercode = cc.customercode 
            order by cc1.priority desc, cc1.insertdate desc
           );

但是,如果是,则假定id为PK(即主键),则等效方法为 MySQL

中的LIMIT子句

类似的东西:

 . . .
where id = (select cc1.id
            from Common_CustomerComments cc1
            where cc1.customercode = cc.customercode 
            order by cc1.priority desc, cc1.insertdate desc
            limit 1
            );