我有两张桌子
注册表
ClientID Name Incube
----------------------
1 Joe as
2 Jack gt
3 Jor ee
存款
DepositID ClientID Quantum
----------------------------
1 1 100.45
2 1 34.5
3 1 22.0
4 2 1000.0
我想得到一个结果,这是 表格注册表中的名称,Incube以及该人员所有存款的总和都与某个ClientID相对应
首先我做了2次查询
SELECT [Name],[Incube] FROM Registry WHERE [ClientID] = 1;
SELECT DISTINCTROW Sum([Deposit].[Quantum]) As Total FROM Deposit WHERE [ClienteID] = 1;
然后我做了一个左连接以使所有事情变得更容易
SELECT
[a].[ClientID],
[a].[Name],
[a].[Incube],
Sum([b].[Quantum]) as Total
FROM Registry a
LEFT JOIN Deposit b
ON a.ClientID=b.ClientID
group by a.Name, a.ClientID, a.Incube;
如何过滤de WHERE子句?我想得到ClientID = 1的所有数据,而不是全部,这里的问题是如何只计算必要的ClientID而不是所有的clientID?
答案 0 :(得分:2)
除非我遗漏了某些内容,否则您只需要添加WHERE
子句:
SELECT
[a].[ClientID],
[a].[Name],
[a].[Incube],
Sum([b].[Quantum]) as Total
FROM Registry a
LEFT JOIN Deposit b
ON a.ClientID=b.ClientID
where a.clientid = 1
group by a.Name, a.ClientID, a.Incube;
结果是:
| CLIENTID | NAME | INCUBE | TOTAL |
-------------------------------------
| 1 | Joe | as | 156.95 |
答案 1 :(得分:1)
出于您的目的,完全不需要左连接。仅在需要不匹配的列时使用它。只需内连接就可以了,
select r.ClientID,r.Name,r.Incube,nvl(sum(d.Quantum),0) as quantum
from Registry r,Deposit d where r.clientId=d.clientID
and r.clientID=1
group by r.clientID,r.Name,r.Incube;