I have this query:
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a
ON a.person_id = p.id ADN
WHERE p.id = 1
GROUP BY p.id;
How can I add condition on account have an valid bank_name
by cheking the bank
table ON account.bank_name = bank.name
to both accounts
and active_accounts
values?
this is db scheme:
Person (
id
)
Account (
id
person_id
state -- 0 - active, 1 - closed
bank_name
)
Bank (
id,
name
)
If Account
have incorrect bank_name
(there are no such row in Bank
table) it shouldn't be counted.
Somethings like this, add left join to bank table and a where clause to check if name is not null :
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a ON
a.person_id = p.id
LEFT JOIN bank b ON
a.bank_name = b.name
WHERE p.id = 1 and
b.name is not null
GROUP BY p.id
see http://sqlfiddle.com/#!9/2b43b3/3
SELECT
p.id,
COUNT(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
FROM Person p
LEFT JOIN Account a ON a.person_id = p.id
INNER JOIN Bank on a.bank_name = Bank.name
WHERE p.id = 1
GROUP BY p.id;
A saner ddl would be smth like this with use of foreign keys
create table person (
id int unique not null
);
create table bank (
id int unique not null,
name nvarchar(10)
);
create table account (
id int unique not null,
person_id int,
state bit,
bank_id int,
FOREIGN KEY (bank_id) REFERENCES bank(id),
FOREIGN KEY (person_id) REFERENCES person(id)
);
Insert into person values (1), (2);
insert into bank VALUES (1, "B1"),(2, "B2");
insert into account values (1,1,1,1), (2,1,0,1),(3,1,1,1),(4,2,1,1);
This kind of DDL will allow you to have accounts
without banks ( bank_id
== null) or accounts
with valid bank_ids
- the DB takes care of it for you - no need for the unsecure join on ncharchar()s - which might go wrong if you commit some trailing/leading spaces
Another way with CTE (if your Database support it) :
with account_valid as (
select
a.*
from
Account a
inner join bank b on
a.bank_name = b.name
)
select
p.id,
count(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
from
Person p
left join account_valid a ON
a.person_id = p.id ADN
where
p.id = 1 -- condition just for test
group by
p.id
or with nested query :
select
p.id,
count(a.id) accounts,
sum(case when a.state = '0' then 1 else 0 end) active_accounts
from
Person p
left join (
select
a.*
from
Account a
inner join bank b on
a.bank_name = b.name
) account_valid a ON
a.person_id = p.id ADN
where
p.id = 1 -- condition just for test
group by
p.id
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.