Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
frank.svs
Constraint Violating Yak Guru
368 Posts |
Posted - 2007-11-26 : 08:12:16
|
| Hi pals,I have a datawarehouse database in which two tables are there.One is "Src" table and other "trg" serves as target table.select * from src ssn distcode fee dt101 1 0 NULL101 1 0 NULL101 1 5 2007-11-26 00:00:00.000101 1 10 2007-11-26 00:00:00.000I loaded the ssn and reposelect * from trgssn distcode tot_fee101 1 NULLNow i need to update the total_fee field based on below conditionsinital calculation:------------------- sum of fee where "dt" is null group by ssn,distcode.Note: is the above sum is zero then consider below secondary calculationSecondary calculation:------------------------ sum of "fee" where "dt" = max of dt in the "Src" table group by ssn,distcode Note: is the sum is zero store zero itself.for the above requirement i have used the below update statement. This is working fine. If u observe the below query the "src" table is loading 3 times.can we optimize this query? Can we avoid these multiple loading of the same table into memory?--- update trg set total_fee =( select case sum(b.fee) when 0 then --------- secondary condition (select case sum(c.fee) when 0.0 then 0.0 else sum(c.fee) end from src c where c.dt = (select max(dt) from src) and c.ssn=a.ssn and c.distcode=a.distcode)-------- else sum(b.fee) end from src b where b.dt is null and b.ssn=a.ssn and b.distcode=a.distcode) from trg a Any suggestions are greatly appreciatedThanks and Regards, |
|
|
kutumbarao
Starting Member
13 Posts |
Posted - 2007-11-26 : 23:53:47
|
| Hi frank,Please try with thisUPDATE trg SET total_fee = S.total_feeFROM trg TINNER JOIN( SELECT A.ssn,A.distcode, COALESCE ( -- FIRST CONDITION (CASE WHEN SUM(CASE WHEN A.dt IS NULL THEN fee ELSE 0 END) = 0 THEN NULL ELSE SUM(CASE WHEN A.dt IS NULL THEN fee ELSE 0 END) END), -- SECOND CONDITION (CASE WHEN SUM(CASE WHEN M.dt IS NOT NULL THEN fee ELSE 0 END) = 0 THEN NULL ELSE SUM(CASE WHEN M.dt IS NOT NULL THEN fee ELSE 0 END) END), -- LAST CONDITION SUM(fee) ) AS total_fee FROM src A LEFT JOIN (SELECT ssn,distcode, MAX(dt) dt FROM src GROUP BY ssn,distcode) M ON M.ssn = A.ssn AND M.distcode = A.distcode AND M.dt = A.dt Group By A.ssn, A.distcode) S ON S.ssn = T.ssn AND S.distcode = T.distcode |
 |
|
|
|
|
|
|
|