获取列最高的不同记录

时间:2015-01-26 21:06:27

标签: sql-server

我有一个列表,我希望每个不同(月)列获得最高的美元金额。有没有一种简单的方法来捕获SQL Server中的记录?

原始表

ID  ProjID  Month   Spent
1   14  Oct  $11,846.00 
1   6   Oct  $82,000.00 
2   8   Nov  $6,051,645.00 
2   9   Nov  $408,744.00 
3   7   Dec  $165,827.00 
3   6   Dec  $485,160.00 
4   1   Jan  $10,300.00 
4   7   Jan  $249,656.00 

期望的结果

ID  ProjID  Month   Spent

1   6   Oct  $82,000.00 
2   8   Nov  $6,051,645.00 
3   6   Dec  $485,160.00 
4   7   Jan  $249,656.00 

我尝试的以下查询显示所有记录。

SELECT
    [MAX_T].[ID],
    [MAX_T].[ProjID],
    [MAX_T].[Month],
    [MAX_T].[MaxSpent]
FROM
    @Table1 [T] INNER JOIN
    (SELECT [ID], [ProjID], [Month], MAX([Spent]) AS [MaxSpent]
    FROM @Table1
    GROUP BY [ID], [ProjID], [Month]) AS [MAX_T]
    ON [T].[ProjID] = [MAX_T].[ProjID] AND
       [T].[Month] = [MAX_T].[Month] AND
       [T].[Spent] = [MAX_T].[MaxSpent]

3 个答案:

答案 0 :(得分:2)

使用ROW_NUMBER

;WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Spent DESC)
    FROM dbo.YourTable
)
SELECT  ID,
        ProjID,
        [Month],
        Spent
FROM CTE
WHERE RN = 1;

答案 1 :(得分:0)

另一种方法是考虑集合中的数据:

第1次获得每月最高美元的套装,然后将该套装加回到基本套件中以获取附加数据......

SELECT A.* 
FROM @TABLE A
INNER JOIN (
  SELECT Month, Max(Spent) as MSpent
  FROM @Table1
  GROUP BY Month) B
on B.Month = A.Month, B.MSpent = A.Spent

答案 2 :(得分:0)

我就这样做了:

select ID, ProjID, Month, Spent, RowNo 
from (
    select ID, ProjID, Month, Spent,
        ROW_NUMBER ()
        over (
            PARTITION BY Month
            order by Spent DESC
            ) as RowNo 

    from (
        select ID, ProjID, Month, Spent
        from Table1
    )
    where RowNo = 1
)

这是未经测试的代码 - 我只是替换了我的字段名称。