表A包含客户名称,服务日期和诊断。
如果要换油,我想选择客户,服务日期和该天的所有诊断。如果不进行换油,我什么都不想要。
我尝试过
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')
预期产量
答案 0 :(得分:0)
尝试类似
SELECT all.customer, all.servicedate, all.diagnosis
FROM A all INNER JOIN A oilchange
ON all.customer=oilchange.customer AND oilchange.diagnosis='oilchange'
答案 1 :(得分:0)
首先获取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
或使用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'
)
请参见demo。
结果:
> 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
答案 2 :(得分:0)
尝试一下:
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'
答案 3 :(得分:0)
如果我理解正确的话
首先确定换油的客户
;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