【问题标题】:How to combine queries in sql server 2016如何在 sql server 2016 中组合查询
【发布时间】:2019-08-08 16:25:02
【问题描述】:

我在 SQL Server 2016 中有两个生成汇总数据的查询 并希望将它们组合成一个查询 结果。第一个引入特定选举周期的数据, 第二个返回当前月份的数据。我想得到一个 包含选举周期和当前的单个结果集 月份。

    I've tried Union to put the two queries together however there could 
    be duplicate members and I would like to count each member one time.

我已经尝试过 union 语句,但是因为我希望将结果放在单独的列中,所以这种方法不起作用。

    Query 1
select d.note  
      ,isnull(count(distinct d.member_id),0) as '2019 EOY'  
from diary_tab d (nolock)  
left join member_tab m (nolock)  
     on m.member_id = d.member_id  
where year(m.effective_dt) = '2019'  
  and m.election_period = 'EOY'  
group by d.note  

    Query 2  
select d.note  
      ,isnull(count(distinct d.member_id),0) as 'Current MTD'  
from diary_tab d (nolock)  
group by d.note  



    currently I get these results:  
    note      EOY  
    -----     ----  
    Note1       20  
    Note2        5  

    Note      MTD  
    -----     -----  
    Note1       6  
    Note2       2  

    I would like to get this:  

    Note      EOY      MTD  
    -----     ----     -----  
    Note1       20       6  
    Note2        5       2

【问题讨论】:

    标签: sql-server sql-server-2016


    【解决方案1】:

    您可以使用条件聚合:

    select d.note  
      ,[2019 EOY] = isnull(count(distinct CASE WHEN year(m.effective_dt) = 2019 AND m.election_period = 'EOY' THEN d.member_id END),0)
      ,[Current MTD] = isnull(count(distinct d.member_id),0)
    from diary_tab d
    left join member_tab m 
      on m.member_id = d.member_id  
    group by d.note;
    

    (NOLOCK) 不是涡轮增压按钮,可能会导致错误结果。

    【讨论】:

    • 谢谢卢卡斯·索兹达。这就是我一直在寻找的解决方案!
    • @JoeB 很高兴听到这个消息。请考虑accepting the answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多