0

以下查询有效,但必须有更好的方法将表的值设置为两组数据联合的最大日期。这是我所拥有的:

Update stagingTable
Set OverrideFlag = 
(
select total.overrideflag from
    (
    select Customer_SSN as ssn, RequestDateTime as maxdate, overrideflag
    from tableA
    where RequestDateTime > '9/1/2012'
    union
    select ssn, EntryDate as maxdate, overrideflag
    from tableB
    where EntryDate > '9/1/2012'
    )  total
    join
    (
    select ssn, max(maxdate) as maxdate from
        (
        select Customer_SSN as ssn, RequestDateTime as maxdate
        from tableA
        where RequestDateTime > '9/1/2012'
        union
        select ssn, EntryDate as maxdate
        from tableB
        where EntryDate > '9/1/2012'
        ) maxs
        group by ssn
    ) maxdates  on total.ssn = maxdates.ssn and total.maxdate = maxdates.maxdate        where total.ssn = stagingTable.ssn
)
4

2 回答 2

0

我还找到了一种使用临时表的不同方法。我对这些感到非常自在,但我总是想看到一种不同的方式来做到这一点。没有失望!

create table #tOvr(customerID varchar(15), ssn varchar(11), EntryDate datetime, overrideflag varchar(2))
insert into #tOvr
select customer_ID, Customer_SSN, RequestDateTime, overrideflag
from tableA
where RequestDateTime > '9/1/2012'
and Customer_ID in 
    (select contact_ID from stagingTable
    where Location_ID = @Location_ID)
insert into #tOvr
select Customer_ID, ssn, EntryDate, overrideflag
from tableB
where EntryDate > '9/1/2012'
and Customer_ID in 
    (select contact_ID from stagingTable
    where Location_ID = @Location_ID)

Update stagingTable
Set OverrideFlag =
    (select overrideflag from #tOvr
    where EntryDate = (select max(EntryDate) from #tOvr where #tOvr.customerID = stagingTable.contact_ID)
    )
于 2013-03-27T19:15:06.170 回答
0

看来你做了两次完全相同的事情,所以我不需要定义两次并将其连接回自身,除非其中一个嵌套选择中有不同的东西。您实际上是在两次编写相同的语句,并且冗余可能是一个问题,因为其中一个选择似乎完全冗余。

-- this is a CTE and is better for reuse than a nested select as you can reference it
-- is as a base and reuse that, versus having to write the same statement twice.
;with a as 
    (
     select 
         Customer_SSN as ssn, 
         RequestDateTime as maxdate, 
         OverRideFlag,
         -- EDIT, you should be able to use a 'Windowed function' to get the maxDate
         max(RequestDateTime) over(partition by SSN order by RequestDateTime desc) as maxDate
     from tableA
     where RequestDateTime > '9/1/2012'
     union
     select 
          ssn, 
          EntryDate, 
          OverRideFlag, 
          max(RequestDateTime) over(partition by SSN order by RequestDateTime desc) as maxDate
     from tableB
     where EntryDate > '9/1/2012'
    )
Update stagingTable
Set OverrideFlag = total.overrideflag
from a total
   join stagingTable on total.ssn = stagingTable.ssn  
   -- do not know reference here so you need to add that table as a 'join' 
where total.EntryDate = total.maxDate
于 2013-03-25T16:04:54.153 回答