因此,如果之前有人问过我,我事先表示歉意...
由于此人始终具有相同的ID,所以只有“人”会更干净。
注意事项:
我尝试过的:
select person = personal_id,
Accounts18 = count(a.Account_ID),
Accounts17 = count(b.Account_ID),
Accounts16 = count(c.Account_ID),
Transac18 = a.Transactions,
Transac17 = b.Transactions,
Transac16 = c.Transactions
from
(select personal_id, account_id, transactions from dbo.bank2018 group by personal_id) a
inner join
(select personal_id, account_id, transactions from dbo.bank2017 group by personal_id) b
on a.personal_id = b.personal_id
inner join
(select personal_id, account_id, transactions from dbo.bank2016 group by personal_id) c
on b.personal_id = c.personal_id
group by person???
谢谢大家!
我认为您希望每一列都计数。如果是这样,则所有工作都在子查询中完成:
select b2018.personal_id, b2018.num_accounts_2018, b2018.num_transactions_2018,
b2017.num_accounts_2017, b2017.num_transactions_2017,
b2016.num_accounts_2016, b2016.num_transactions_2016
from (select personal_id,
count(distinct account_id) as num_accounts_2018,
count(*) as num_transactions_2018
from dbo.bank2018
group by personal_id
) b2018 inner join
(select personal_id,
count(distinct account_id) as num_accounts_2017,
count(*) as num_transactions_2017
from dbo.bank2017
group by personal_id
) b2017
on b2017.personal_id = b2018.personal_id inner join
(select personal_id,
count(distinct account_id) as num_accounts_2016,
count(*) as num_transactions_2016
from dbo.bank2016
group by personal_id
) b2016
on b2016.personal_id = b2017.personal_id;
注意,这只会返回在所有三个表中都有数据的人。如果希望一个或多个表中缺少的客户,则需要某种外部联接。