[英]How to select records only if a specific condition is met
Table A has customer names, service dates, and diagnosis. 表A具有客户名称,服务日期和诊断。
I want to select the customer, the date of service and all diagnosis for that particular day if an oil change was done. 如果换了机油,我想选择客户,服务日期和该天的所有诊断。 If an oil change was not done, I don't want anything at all.
如果不换油,我什么都不要。
I have tried 我努力了
select customer, servicedate, diagnosis
from A
where customer in (select customer from A where diagnosis = 'oilchange')
and servicedate in (select servicedate from A where diagnosis = 'oilchange')
Expected Output 预期产量
Try something like 尝试类似
SELECT all.customer, all.servicedate, all.diagnosis
FROM A all INNER JOIN A oilchange
ON all.customer=oilchange.customer AND oilchange.diagnosis='oilchange'
First get the dates and customers where there is diagnosis = 'oil change'
and join to the table: 首先获取
diagnosis = 'oil change'
的日期和客户,然后加入表格:
select A.customer, A.servicedate, A.diagnosis
from A inner join (
select customer, servicedate
from A
where diagnosis = 'oil change'
) B on B.customer = A.customer and B.servicedate = A.servicedate
Or with EXISTS: 或存在时:
select t.customer, t.servicedate, t.diagnosis
from A t
where exists (
select 1 from A
where customer = t.customer and servicedate = t.servicedate and diagnosis = 'oil change'
)
See the demo . 参见演示 。
Results: 结果:
> customer | servicedate | diagnosis
> :------- | :------------------ | :----------
> Smith | 01/01/2019 00:00:00 | Spark plugs
> Smith | 01/01/2019 00:00:00 | ValveCG
> Smith | 01/01/2019 00:00:00 | oil change
> Smith | 01/01/2019 00:00:00 | alignment
> John | 06/01/2019 00:00:00 | puncture
> John | 06/01/2019 00:00:00 | oil change
> John | 06/01/2019 00:00:00 | Wipers
> John | 06/01/2019 00:00:00 | engine
Try this: 尝试这个:
select customer, servicedate, diagnosis
from A as a1, A as a2
where a1.customer = a2.customer and a1.servicedate = a2.servicedate and a2.diagnosis = 'oilchange'
if I understand this correctly 如果我正确理解这一点
First identify the customers who had an oil change 首先确定换油的客户
;with OilChange
AS(
select customer, servicedate
from A
where diagnosis = 'oilchange'
)
--then get the rest of the data
select tbl.customer, tbl.servicedate, tbl.diagnosis
from A tbl
INNER JOIN OilChange OC on OC.Customer = tbl.Customer and OC.Servicedate = tbl.ServiceDate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.