【问题标题】:SQL Server subquery result outputSQL Server 子查询结果输出
【发布时间】:2018-05-15 18:55:07
【问题描述】:

我想创建一个结果,列出昨天添加到数据库的所有客户,然后为同一组客户创建一个单独的列,但只有那些没有电子邮件地址的客户,这样我们就可以看到哪个 CSR 代表没有添加电子邮件地址,我在编写计数子查询时遇到问题。下面是我的代码,它使用两个表 CLIENT 和 CONTACT 他们加入 ACCT_NO 字段

我正在使用 SQL Server Management Studio

select 
    count(distinct c.acct_no) as Total, ADDED_BY 
from 
    client c
inner join 
    (select 
         count(distinct ct.acct_no) acct_NO 
     from 
         contact CT 
     inner join 
         client on client.acct_no = ct.ACCT_NO 
                and ct.EMAILADDR1 = ''
                and ct.[PRIMARY] = 'A' 
     group by 
         ct.ACCT_NO) x on c.ACCT_NO = x.acct_NO 
where 
    c.DATE_ADDED = CONVERT(varchar(10), GETDATE()-10, 121)
group by 
    c.ADDED_BY

【问题讨论】:

  • 样本数据和期望的结果真的很有帮助。

标签: sql sql-server ssms


【解决方案1】:

您可以使用count(distinct case ... 进行条件总和,例如:

select  ADDED_BY
,       count(distinct case when client.EMAILADDR1 is null then client.ACCT_NO end) 
            as TotalWithoutMail
,       count(distinct case when client.EMAILADDR1 is not null then client.ACCT_NO end) 
            as TotalWithMail
from    contact
jon     client
on      client.ACCT_NO = contact.ACCT_NO
group by
        ADDED_BY

【讨论】:

  • 这没有给我预期的结果,我正在寻找看起来像 ADDED_BY、添加的客户总数、添加的没有电子邮件的客户总数
  • 做了一些调整,但现在可以正常工作了,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-05
  • 2011-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
相关资源
最近更新 更多