TSQL Union,Max(日期) - 有解决方案。想要改进

时间:2013-03-25 15:20:03

标签: sql-server tsql union max

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

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
)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)
    )