sql—包含当前数据的指示符,但不包含在结果中

z4bn682m  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(416)

我不能很好地解释它,因此标题很糟糕。
举个例子,我会有一个查询,显示某一类型的客户投诉,以及这些投诉发生的日期。如下所示:

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 |否
可能只是问了个愚蠢的问题,但我需要知道。谢谢。

velaa5lx

velaa5lx1#

您可以从 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

相关问题