Hi,I have two tables:declare @a table (id char(4), v_on decimal(7,2), v_of decimal(7,2), evt_cde int)insert @aselect '4838', 0, 8, 2120001 union allselect '4838', 1, 22, 2122001 union allselect '4838', 6, 3, 2122002 union allselect '4838', 0, 6, 2122003 union allselect '4838', 47, 7, 2122121 union allselect '4838', 22, 0, 2122122 union allselect '4838', 0, 2, 2122125 union allselect '4838', 76, 42, NULL union allselect '4838', 76, 42, NULL union allselect '4118', 0, 7.5, 2120001 union allselect '4118', 0, 46, 2122001 union allselect '4118', 0, 54, 2122002 union allselect '4118', 0, 13, 2122003 union allselect '4118', 20, 21, 2122121 union allselect '4118', 8, 28, 2122122 union allselect '4118', 34, 37, 2122123 union allselect '4118',105, 23, 2122125 union allselect '4118',167, 216.5, NULL union allselect '4118',167, 216.5, NULLdeclare @b table (cde int, dsc varchar(40))insert @bselect 2120001, 'grav' union allselect 2122001, 'pre-pl' union allselect 2122002, 're pre' union allselect 2122003, 're re' union allselect 2122121, 'comp' union allselect 2122122, 'fala' union allselect 2122123, 'co-re' union allselect 2122124, 'outr' union allselect 2122125, 'ojco'
I need to extract records from @a, grouped by id - here I'll have two records ('4838' and '4118').In addition to id, I'll also need four more fields, which are SUMed v_of and v_on.To know which v_on / v_of is included in which SUM, I join @b on @a.evt_cde = @b.cde (@b is in effect a lookup table, I only need records that have values in @a).Now - if (@b.dsc NOT like 'gr%' and @b.dsc NOT like 're re%') - I use v_on and v_of for fields VA and VB.If (@b.dsc like 're re%') - I use v_on and v_of for fields VC and VD.So here my intermediate table (both joined) for '4838' would look like this:id v_on v_of evt_cde dsc AB CD---- --------- --------- ----------- ----------- ---- ----4838 .00 8.00 2120001 'grav' 4838 1.00 22.00 2122001 'pre-pl' Y 4838 6.00 3.00 2122002 're pre' Y 4838 .00 6.00 2122003 're re' Y4838 47.00 7.00 2122121 'comp' Y 4838 22.00 .00 2122122 'fala' Y 4838 .00 2.00 2122125 'ojco' Y 4838 76.00 42.00 NULL NULL Y 4838 76.00 42.00 NULL NULL Y
Column AB indicates if v_on and v_off are used for VA / VB, CD if they are used for VC / VD.VA is sum of v_on where AB=YVB is sum of v_of where AB=YVC is sum of v_on where CD=YVD is sum of v_of where CD=YOne more thing: table @b is on another server, and I use it via OPENDATASOURCE; it's a very small table (unlike the @a).How do I write such query? The NULLs in the @a are getting me in the way...TIA