我正在尝试为每个位置找到特定用户的最后一个条目。我还需要忽略余额为零的任何行。
样本表:
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
需要的结果:
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
我只能为一位生病的同事辩护,不幸的是我的SQL知识相对有限。
我一直在研究使用MAX和PARTITION BY但到目前为止没有运气。这适用于SQL Server 2005数据库。
对此的任何帮助将不胜感激。我将添加任何进展。
非常感谢。
答案 0 :(得分: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
答案 1 :(得分: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;
答案 2 :(得分: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 )