SQL查询显示仅存1笔存款且仅存1笔的客户

时间:2014-02-03 10:17:03

标签: sql

我有一个安静的大型数据库,只有很少的表,我正在尝试运行一个查询,显示只有1次存款的客户列表。所以我联合两个表是客户其他存款。

客户表:

id,firstName,LastName,Email,Tel等.....

存款表:

id,customerId,amount,confirmTime等.....

SQL查询......

select
customer.id as 'Customer ID',
(select count(deposits.customerId) from deposits
where customer.id=deposits.customerId) as 'No. of Deposits',

deposits.amount as 'Deposit Amount',
deposits.confirmTime as 'Confirmation TIme'

from customer

left join deposits on customer.id=deposits.customerid

group by customer.id

此查询返回一个很好的列表,其中包含存款数量和日期的所有客户,问题是查询带来了我想要查询的所有存款数量,只显示客户哪里没有。存款= 1

但是我遇到了问题,因此无法想出实现这一目标的正确途径。

1 个答案:

答案 0 :(得分:1)

您可以将所有查询作为子查询并为其列添加别名。我在这里写,:

    select tab.ID as 'Customer ID',tab.count as  'No. of Deposits',
    tab.dmt as 'Deposit Amount', tab.ct as 'Confirmation TIme' from 

    (select customer.id as ID,(select count(deposits.customerId) from deposits where 
    customer.id=deposits.customerId) as count, 
    deposits.amount as dmt,deposits.confirmTime 
    as ct from customer left join deposits on customer.id=deposits.customerid group by 
     customer.id)as tab where tab.count=1;

如果它没有帮助你那么让我知道我会告诉你另一种方式。

相关问题