我有两个名为SavingAccountTransactions和LoanAccountTransactions的表。
两个表都有相同的列(fk_MemberId,fk_AgentId,TransactionDate)
样本数据
SavingAccountTransactions表
Id fk_MemberId fk_AgentId TransactionDate Amount
--- ----------- ----------- --------------- -------
1 441 12 2014-12-30 100
2 452 6 2014-12-30 300
LoanAccountTransactions表
Id fk_MemberId fk_AgentId TransactionDate Amount
--- ----------- ----------- --------------- -------
1 441 12 2014-12-30 500
2 452 6 2014-12-30 200
如何将SavingAccountTransactions和LoanAccountTransactions表结合起来,为特定成员在一行中获取 NoOfMembersVisited 的计数。
以下是我试过的查询
select u.Fullname as AgentName ,count (distinct t.fk_MemberId ) as NoOfMembersVisited
from dbo.SavingAccountTransactions T
inner join Users u on t.fk_AgentId=u.Id
where t.TransactionDate = CAST(GETDATE() AS DATE)
group by u.Fullname
Union all
select u.Fullname as AgentName, count (distinct l.fk_MemberId ) as NoOfMembersVisited
from LoanAccountTransactions L
inner join Users u on L.fk_AgentId=u.Id
where l.TransactionDate = CAST(GETDATE() AS DATE)
group by u.Fullname
预期结果:
AgentName NoOfMembersVisited
--------- -------------------
John 2
Kevin 1
etc....
答案 0 :(得分:0)
因为您没有提供任何样本数据,所以很难知道您得到了什么。但我可能知道你的问题是什么。当您使用UNION ALL
时,如果用户同时在这两个表中,则会重复这些用户。因为将UNION ALL
更改为UNION
的表格可能会有不同的计数。我想建议你做这样的事情:
;WITH CTE
AS
(
select u.Fullname as AgentName,l.fk_MemberId
from dbo.SavingAccountTransactions T
inner join Users u on t.fk_AgentId=u.Id
where t.TransactionDate = CAST(GETDATE() AS DATE)
UNION ALL
select u.Fullname as AgentName,l.fk_MemberId
from LoanAccountTransactions L
inner join Users u on L.fk_AgentId=u.Id
where l.TransactionDate = CAST(GETDATE() AS DATE)
)
SELECT
CTE.Fullname,
COUNT(distinct CTE.fk_MemberId) as NoOfMembersVisited
FROM
CTE
group by
CTE.Fullname