如何在sql记录中获取每个用户的单个记录

时间:2013-12-04 13:23:23

标签: sql-server

我必须获取每个用户的单个记录,这是表中的最后一个条目。该表包含每个用户的多条记录。

select userid, UserNM, UserPMobileNo
into #user
from tbUserMaster
where UserStatus = 1


select a.userid, a.UserNM, a.UserPMobileNo, SUM(b.uAmount) as [load]
into #bal
from #user a
  left join tbbalance b on a.UserID = b.UserID and b.uAmount = ABS(b.uAmount)
group by a.UserID, a.UserNM, a.UserPMobileNo


select distinct u.*, sum(b.pTotalAmt ) as [Net Usage]
into #Sale1
from #bal u
  left join tbProcTransactions b on u.UserID = b.pUserID
    and (b.pMessContent not like '%Failure%' or b.pMessContent != 'Failed')
group by u.userid, u.UserNM, u.UserPMobileNo, u.[load], b.pCurrentBalance, b.pTotalAmt


select a.userid, a.UserNM, a.UserPMobileNo, a.[load], (pCurrentBalance + pTotalAmt) as [OB]
into #OB
from tbProcTransactions b
  inner join #bal a on b.pUserID=a.userid 

这里我得到了我想要获取每个用户总金额的最终结果。

select a.userid, a.UserNM, a.UserPMobileNo, a.[load], (pCurrentBalance + pTotalAmt) as [OB]
into #OB
from tbProcTransactions b
  inner join #bal a on b.pUserID = a.userid 

但我获得了100000条记录,但实际记录是4000条。

如何为每位用户获取一条记录?

1 个答案:

答案 0 :(得分:0)

名为[tbProcTransactions]的表每个UserID有多条记录。当您将#bal加入[tbProcTransactions]时,#bar中的每条记录都匹配[tbProcTransactions]中的多条记录,这会导致返回额外的行。

为了限制行数,必须在WHERE语句中指定其他条件。例如:

select a.userid, a.UserNM, a.UserPMobileNo, a.[load], (pCurrentBalance + pTotalAmt) as [OB]
into #OB
from tbProcTransactions b
  inner join #bal a on b.pUserID = a.userid

-- added code, using a timestamp field.
-- If there is a possibility of one user having multiple entries on the same timestamp, you will need to also sort by an auto-numbered field.
-- TODO: change this to the correct DATETIME field name
WHERE b.timestampfield=(
    SELECT MAX(c.timestampfield)
    FROM tbProcTransactions c
    WHERE c.userid=a.userid
)