我无法完全正确地解释它,因此标题很糟糕。
例如,我将查询一个显示特定类型的客户投诉以及这些投诉的发生日期的查询。类似于以下内容:
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 |否
可能只是问一个愚蠢的问题,但需要知道。谢谢。
您可以从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