在sql server中选择最大日期和comprate总和

时间:2012-06-21 04:56:38

标签: sql-server

我试图从以下查询获得max(id)的max(effdt)总和(comprate),

SELECT  id, employee_code, effdt, comprate
FROM         dbo.employees_compensation
WHERE     (employee_code = '000321514')
ORDER BY effdt desc, id desc

以上查询的结果如下,

id      employee_code   effdt                   comprate
1473433 000321514       2010-09-02 00:00:00.000 46000
1473432 000321514       2010-09-02 00:00:00.000 138000
1453627 000321514       2010-09-02 00:00:00.000 46000
1453626 000321514       2010-09-02 00:00:00.000 138000
1447165 000321514       2010-09-02 00:00:00.000 46000
1447164 000321514       2010-09-02 00:00:00.000 138000
1424948 000321514       2010-09-02 00:00:00.000 46000
1424947 000321514       2010-09-02 00:00:00.000 138000
1405789 000321514       2010-09-02 00:00:00.000 46000
1405788 000321514       2010-09-02 00:00:00.000 138000

我尝试了很多查询,但我没有得到预期的结果。我想要的是上面结果的前两个值,即

id    employee_code effdt                   comprate
1473433 000321514   2010-09-02 00:00:00.000 46000
1473432 000321514   2010-09-02 00:00:00.000 138000

然后从上面的结果得到总和(comprate),即

sum(comprate)
184000

你能帮助我获得预期的结果吗?在此先感谢。

3 个答案:

答案 0 :(得分:0)

我建议您查看如何限制结果集的大小LIMIT 10..20 in SQL Server。然后,如何在此处对子查询进行计算http://www.sqlteam.com/article/aggregating-correlated-sub-queries

答案 1 :(得分:0)

如果您使用的是SQL Server 2005 或更新版(您未在问题中指定),则可以使用带有ROW_NUMBER功能的CTE(公用表表达式):

;WITH OrderedData AS
(
   SELECT 
       id, employee_code, effdt, comprate,
       RowNum = ROW_NUMBER() OVER(ORDER BY effdt DESC, id DESC) 
   FROM         
       dbo.employees_compensation
   WHERE     
      employee_code = '000321514'
   FROM dbo.YourTable
)
SELECT 
   SUM(comprate)
FROM  
   OrderedData
WHERE 
   RowNum <= 2

此CTE会为您的数据和ROW_NUMBER功能订购序列号,从1开始并按effdt DESC, id DESC排序 - 因此最新行(最新effdt和最高id获得RowNum = 1。那么我基本上选择前两行并总结它们。

答案 2 :(得分:0)

以下怎么样?

SELECT     SUM(comprate) AS ComprateSum
FROM         (SELECT     TOP (2) id, employee_code, effdt, comprate
                       FROM          _Test
                       WHERE      (employee_code = '000321514')
                       ORDER BY effdt DESC, id DESC) AS derivedtbl_1