首页 > 解决方案 > 包括存在数据的指标,但不包括在结果中

问题描述

我不能完全正确地解释它,因此这个可怕的标题。

例如,我会有一个查询,显示某种类型的客户投诉以及这些投诉后的日期。类似于以下内容:

select * from( select c.firstname, c.lastname , max(ont.date1) as "LastDate", 
DATEDIFF(DAY, MAX(ont.Date1), SYSDATETIME()) AS "Days"

from [ComplaintInfo] ci
inner join [OrderNotes] ont on ont.orderid = ci.orderid
inner join [Customers] c on c.custid = ci.custid
right outer join [CustLive] cl on ont.custidl = cl.custidl
where (ci.typeofcomp = '2' or ci.typeofcomp = '3')
and (ont.answertype <> '2' and ont.answertype <> '3' and ont.answertype <>'4'
group by c.lastname, c.firstname
)   Sub
where Days >= 5
order by Days, sub.lastname asc

这会给出类似的东西

约翰 | 史密斯 | 2020-06-03T13:00:00 | 1

特里 | 琼斯 | 2020-05-04T:04:00:00 | 30

但是,虽然我希望 typeoforder 不是 2 或 3,并且我不希望它们包含在我的结果集中,但我想知道是否有任何这些类型的订单。所以,例如,如果

约翰 | 史密斯 |2020-06-03T13:00:00 | 1 | 是的

特里 | 琼斯 | 2020-05-04-04:00:00 | 30 | 不

可能只是问一个愚蠢的问题,但需要知道。谢谢。

标签: sqlsql-servertsqljoin

解决方案


您可以从where子句中删除条件并使用条件表达式:

select 
    c.firstname, 
    c.lastname, 
    max(ont.date1) as LastDate 
    datediff(day, max(ont.date1), sysdatetime()) as days,
    max(case when ci.typeofcomp = 2 or ci.typeofcomp = 3 then 'Yes' else 'No' end) hasTypeOfComp_2_Or_3
from [ComplaintInfo] ci
inner join [OrderNotes] ont on ont.orderid = ci.orderid
inner join [Customers] c on c.custid = ci.custid
right outer join [CustLive] cl on ont.custidl = cl.custidl
where ont.answertype <> 2 and ont.answertype <> 3 and ont.answertype <> 4
group by c.lastname, c.firstname

笔记:

  • 我删除了数字周围的单引号 - 因为它们看起来像数字,我假设它们是这样存储的,在这种情况下你想将它们与文字数字进行比较(如果不是这样,你可以把引号放回去)

  • 我怀疑right outer join:这真的是你想要的吗?如果没有,只需使用inner join


推荐阅读