我有一个小的SQL查询,就像这样
SELECT * FROM table
这会返回一堆结果,我输出以下字段:
ID
UserID
Amount
Date
我想要做的是从每个UserID(基于ID)获取最新条目,然后如果金额为0,则不返回该UserID的任何结果。
答案 0 :(得分:1)
select t1.*
from your_table t1
join
(
select userid, max(date) as mdate
from your_table
group by userid
having sum(case when amount = 0 then 1 else 0 end) = 0
) t2 on t1.userid = t2.userid and t1.date = t2.mdate
在用户分组的子查询中,只选择那些没有零的子查询。在该选择中,您使用max(date) as mdate
获取每个用户的最新日期。
该子查询可以连接到原始表以获取完整记录,而不仅仅是用户ID。
答案 1 :(得分:0)
试试这个
WITH cte AS
(
SELECT
MAX(ID) OVER (PARTITION BY UserID) MaxIDForUserID,
ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY ID DESC) rn,
UserID,
Amount,
Date
FROM TableName
)
SELECT * FROM cte WHERE rn = 1 AND Amount != 0