0

I am trying to find the last entry for a specific user for each location. I also need to ignore any rows where the balance is zero.

Sample table:

    ID location user balance
    -- -------- ---- -------
     1 GLA      A    10.21
     2 GLA      A    0.00
     3 GLA      B    45.68
     4 GLA      B    12.56
     5 EDI      C    1.23
     6 EDI      D    5.48
     7 EDI      D    0.00
     8 LON      E    78.59
     9 MAN      F    0.00
    10 MAN      F    12.98
    11 MAN      G    56.45
    12 MAN      G    89.25
    13 MAN      H    0.00
    14 BIR      I    0.00
    15 BIR      I    32.87

Result required:

    ID location user balance
    -- -------- ---- -------
     4 GLA      B    12.56
     5 EDI      C    1.23
     8 LON      E    78.59
    10 MAN      F    12.98
    12 MAN      G    89.25
    15 BIR      I    32.87

I have been left to cover for a colleague who is off sick and unfotunately my SQL knowledge is limited in comparison.

I have been researching using MAX and PARTITION BY but with no luck so far. This is for a SQL Server 2005 database.

Any assistance with this would be greatly appreciated. I will add any progress I make.

Many Thanks.

4

3 回答 3

5

您应该能够使用row_number()来获得结果:

select id, location, [user], balance
from 
(
  select id, location, [user], balance,
    row_number() over(partition by location, [user]
                        order by id desc) seq
  from yourtable
) d
where seq = 1
  and balance <> 0
order by id;

请参阅带有演示的 SQL Fiddle

于 2013-07-31T12:19:28.057 回答
5
Select   
      A.ID ,
      A.location,
      A.[user] ,
      A.balance from TABLE1 A 
     inner join (
                 Select Max(Id) AS Id from TABLE1 
                 group by location,[user]
                 ) B 
      on A.ID=B.ID 
      WHERE A.Balance>0

Sql 小提琴演示

于 2013-07-31T12:14:17.443 回答
0

使用Row_Number()函数:

SELECT id,
   location,
   user,
   balance
FROM   ( SELECT ROW_NUMBER( )
              OVER (
                PARTITION BY user
                ORDER BY id DESC ) AS rowid,
            *
     FROM   tableA ) AS data
WHERE  ( rowid = 1 )
   AND ( balance > 0 )
于 2013-07-31T12:33:46.407 回答