我正在进行sql server查询,其中我有2个表
tblUsers(ID,Name)
tblPayments(ID,User_ID,Date,Amount)
我想获得每个用户提供的最后一笔付款。为此,我使用了以下查询 -
select distinct tblPayments.* from tblPayments inner join tblUsers on
tblUsers.ID=tblPayments.User_ID
但上述查询返回用户提供的所有付款。但我想每个用户只需支付一笔款项,即用户上次付款。任何人都可以帮助我。
答案 0 :(得分:1)
尝试此查询
select tblPayments.* from tblPayments
inner join(select Userid,max(id) as id
from tblPayments group by Userid) a on a.id=tblPayments.id
答案 1 :(得分:1)
您可以尝试以下查询来获取每个用户的最后一笔付款
CREATE TABLE tblUsers (ID INT, NAME VARCHAR(20))
CREATE TABLE tblPayments(ID INT, User_Id INT, OrderDATE DATE, Payment Decimal)
INSERT INTO tblUsers VALUES (1,'User 1'),(2,'User 2')
INSERT INTO tblPayments VALUES (1,1,'2015-05-02',12.0),
(2,1,'2015-05-03',15.0),
(3,2,'2015-05-06',17.0),
(4,2,'2015-05-07',11.0)
SELECT tp1.*, tu.NAME
FROM tblPayments tp1
JOIN (
SELECT User_ID,MAX(OrderDate) AS MaxDate
FROM tblPayments
GROUP BY User_Id) tp2
ON tp1.User_Id = tp2.User_Id
AND tp1.OrderDATE = tp2.MaxDate
JOIN tblUsers tu
ON tu.ID = tp1.User_Id
答案 2 :(得分:0)
为每个用户获取最新的付款日期(使用交叉申请来实现)然后使用该日期从tblPayments表中单独过滤这些记录。
SELECT b.ID,
b.Date,
b.Amount
FROM tblusers a
JOIN tblPayments b
ON a.ID = b.User_ID
CROSS apply (SELECT Max(Date) AS mx_date
FROM tblPayments c
WHERE a.ID = c.ID) cp
WHERE b.Date = cp.mx_Date
答案 3 :(得分:0)
SQL Row_Number() function with Partition By clause可以帮助我们为每个用户订购付款记录
以下是使用SQL CTE expression
构建Select查询的方法with CTE as (
select
p.User_ID,
u.Name,
p.ID,
p.Date,
p.Amount,
rn = ROW_NUMBER() OVER (Partition By User_ID Order By Date desc)
from tblUsers u
inner join tblPayments p on u.ID = p.User_ID
)
select * from CTE where rn = 1