SQL Max不起作用?

时间:2014-08-22 11:54:50

标签: sql

这是一个非常简单的问题,我很确定。我有一个非常基本的查询

Select MAX(ExposureYear) AS YEAR,
        totalvalue

FROM [dbo].[DetailsView]

我希望它返回2012年的两条记录,但这是我得到的结果:

2009    647564
2009    818418
2009    818481
2012    8465153
2009    11739239
2012    22310900
2009    39305433

我做错了什么?

先谢谢

6 个答案:

答案 0 :(得分:2)

我认为你想要的更像是:

Select ExposureYear, totalvalue
FROM [dbo].[DetailsView]
where ExposureYear = (select MAX(ExposureYear) from DetailsView);

如果视图很昂贵,那么您可以改为使用窗口函数:

select ExposureYear, totalvalue
from (select v.*, max(ExposureYear) over () as maxey
      from [dbo].[DetailsView] v
     ) v
where ExposureYear = maxey;

答案 1 :(得分:1)

MAX不能以这种方式工作,你想要这样的东西:

select * from [dbo].[DetailsView] where exposureyear = 
(select max(exposureyear) from [dbo].[DetailsView])

答案 2 :(得分:0)

SELECT ExposureYear AS YEAR, totalvalue
FROM [dbo].[DetailsView]
WHERE ExposureYear = (SELECT MAX(ExposureYear) From FROM [dbo].[DetailsView])

答案 3 :(得分:0)

您可以尝试这样:

select ExposureYear AS YEAR, totalvalue from [dbo].[DetailsView] where ExposureYear = 
(select max(ExposureYear) from [dbo].[DetailsView])

答案 4 :(得分:0)

如果您的“ exposureYear ”列为varchar data type,则将其更改为int它将正常工作。

答案 5 :(得分:0)

老兄保持简单,只需添加一个小组。

Select MAX(ExposureYear) AS YEAR, totalvalue
FROM [dbo].[DetailsView]
GROUP BY totalvalue