我正在使用一个子查询来避免大约 100 个重复项(在大约 40k 条记录中)。显示重复的记录是因为它们在 h2.datecreated 中有 2 个日期是有正当理由的,所以我不能只清理数据。
我试图只得到最早的返回日期。第一个子查询(以“select distinct address_id”开头,带有 MIN)可以自己正常工作……不返回重复项。所以看起来左连接(或者只是简单的连接......我也试过了)不可能看到第二个 h2.datecreated,因为它甚至没有出现在子查询中。但是当我运行整个查询时,它会返回一些 ipc.mfgid 的 2 个值,一个是我想要的 h2.datecreated,另一个是我不想要的。
我知道这一定是非常简单的事情,或者是不可能的事情。看起来它真的应该工作!这是 MSSQL。谢谢!
select distinct ipc.mfgid as IPC, h2.datecreated,
case when ad.Address is null
then ad.buildingname end as Address, cast(trace.name as varchar)
+ '-' + cast(trace.Number as varchar) as ONT,
c.ACCOUNT_Id,
case when h.datecreated is not null then h.datecreated
else h2.datecreated end as Install
from equipmentjoin as ipc
left join historyjoin as h on ipc.id = h.EQUIPMENT_Id
and h.type like 'add'
left join circuitjoin as c on ipc.ADDRESS_Id = c.ADDRESS_Id
and c.GRADE_Code like '%hpna%'
join (select distinct address_id, equipment_id,
min(datecreated) as datecreated, comment
from history where comment like 'MAC: 5%' group by equipment_id, address_id, comment)
as h2 on c.address_id = h2.address_id
left join (select car.id, infport.name, carport.number, car.PCIRCUITGROUP_Id
from circuit as car (NOLOCK)
join port as carport (NOLOCK) on car.id = carport.CIRCUIT_Id
and carport.name like 'lead%'
and car.GRADE_Id = 29
join circuit as inf (NOLOCK) on car.CCIRCUITGROUP_Id = inf.PCIRCUITGROUP_Id
join port as infport (NOLOCK) on inf.id = infport.CIRCUIT_Id
and infport.name like '%olt%' )
as trace on c.ccircuitgroup_id = trace.pcircuitgroup_id
join addressjoin as ad (NOLOCK) on ipc.address_id = ad.id