MS SQL最后一条记录

时间:2014-11-25 15:52:37

标签: sql sql-server

我只是尝试编写MS SQL语句以从数据库中获取最后的数据,不幸的是,当我添加DESC LIMIT 1时,它说错误的语法,尽管它看起来对我很好。

有更多技能的人可以看一下吗?

Select
  sum(spareparts), 
  month(calculationdate) 
from cz_axnmrs_calculations 
where CASE_ID in (select case_id 
                  from cz_axnmrs_cases 
                  where insurer_memberid = 'MM-O-5B57274F') 
and YEAR(calculationdate)='2014'  
group by month(calculationdate) DESC LIMIT 1

就像这样有效:

Select 
  sum(spareparts), 
  month(calculationdate) 
from cz_axnmrs_calculations 
where CASE_ID in (select case_id 
                  from cz_axnmrs_cases 
                  where insurer_memberid = 'MM-O-5B57274F') 
and YEAR(calculationdate)='2014'  
group by month(calculationdate)

3 个答案:

答案 0 :(得分:4)

SQL Server使用TOP而不是LIMIT来限制记录数。

您的查询变为:

Select top 1 
  sum(spareparts), 
  month(calculationdate) 
from cz_axnmrs_calculations 
where CASE_ID in (select case_id 
                  from cz_axnmrs_cases 
                  where insurer_memberid = 'MM-O-5B57274F') 
and YEAR(calculationdate)='2014'  
group by month(calculationdate) DESC

答案 1 :(得分:2)

在SQL Server 2012+中,Microsoft支持ANSI标准OFFSET子句。你可以这样写:

Select sum(spareparts), month(calculationdate)
from cz_axnmrs_calculations
where CASE_ID in (select case_id from cz_axnmrs_cases where insurer_memberid = 'MM-O-5B57274F') and
      YEAR(calculationdate)='2014'
group by month(calculationdate) DESC
fetch first 1 row only;

答案 2 :(得分:1)

Select TOP 1 sum(spareparts), month(calculationdate) from cz_axnmrs_calculations 
WHERE CASE_ID in (select case_id 
FROM cz_axnmrs_cases WHERE insurer_memberid = 'MM-O-5B57274F') AND YEAR(calculationdate)='2014'  
GROUP BY month(calculationdate)