sql - 包括存在数据的指标,但不包括在结果中
问题描述
我不能完全正确地解释它,因此这个可怕的标题。
例如,我会有一个查询,显示某种类型的客户投诉以及这些投诉后的日期。类似于以下内容:
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
推荐阅读
- c# - 创建目录(在网络驱动程序上)在 IIS 上运行时抛出错误
- java - 如何从java中的字符串中删除特殊字符?
- c++ - 使用 cli 连接到 db2 失败,错误代码为 -1531
- python - 在 DataFrame 中提取包含非数字值的行
- node.js - Highcharts Node.js 导出服务器 - 在 SVG 字符串中获取输出
- kubernetes - 如何禁用 istio 就绪探测
- java - 如何为给定的方法编写测试用例
- android - 资源任务给出错误并且未加载 appcompat-v7
- android - 使用自定义参数实现 AndroidX Worker
- mysql - Laravel 5.8 使用数据透视表的自定义列名的多对多关系