0

次のクエリは機能しますが、テーブルの値を2つのデータセットの和集合の最大日付に設定するためのより良い方法が必要です。これが私が持っているものです:

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

まったく同じことを2回行っているように見えるので、ネストされた選択の1つに何か異なるものがない限り、何かを2回定義してそれ自体に結合する必要はありません。基本的に同じステートメントを2回記述していますが、選択の1つが完全に冗長であるように見えるため、冗長性が問題になる可能性があります。

-- 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 に答える
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 に答える