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.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Nested Query - Sort of

Author  Topic 

mj76
Starting Member

8 Posts

Posted - 2002-08-15 : 16:50:20
I have a sproc that runs just fine, now one of the managers here wants me to tweak it so that it can pull sum totals on 'field b' based upon the contents of 'field a', but have the rest of them stay the same.

I don't want to get into too much detail right away, but is this possible.

pseudo code:

select fields from table, if field A contains the word "remarket" then group just those fields together with an alias, but keep all of the other ones separate

thanks in advance

robvolk
Most Valuable Yak

15732 Posts

Posted - 2002-08-15 : 17:35:54
You'll have to provide some raw data and some sample output, I can't quite see it.

You might be able to use ROLLUP to generate the summary values, but if you have a GROUP BY it will affect ALL of the rows. The only way around that is to have two queries...one with the GROUP BY and the other without...and then UNION them together, but that may also cause problems.

Go to Top of Page

MuffinMan
Posting Yak Master

107 Posts

Posted - 2002-08-15 : 17:46:02
Something like this? (Just guessing here!)


set nocount on

create table #tmp (field_a varchar(20) not null , field_b int, field_c varchar(30))

insert #tmp select 'SQL Team', 0 , 'Website'
insert #tmp select 'remarket' , 10 , 'Video Killed the Radio Star'
insert #tmp select 'CSCO' , 15 , 'CISCO Systems'
insert #tmp select 'remarket' , 55 , 'It''s the shoes, Money!'

print '** original select **'
select * from #tmp

print ''
print '** Select with SUM **'
select *
, sum_field = case
when field_a = 'remarket'
then (select sum(field_b)
from #tmp
where field_a = 'remarket') else NULL end
from #tmp


-- drop table #tmp

/* here are the results */
** original select **
field_a field_b field_c
-------------------- ----------- ------------------------------
SQL Team 0 Website
remarket 10 Video Killed the Radio Star
CSCO 15 CISCO Systems
remarket 55 It's the shoes, Money!


** Select with SUM **
field_a field_b field_c sum_field
-------------------- ----------- ------------------------------ -----------
SQL Team 0 Website NULL
remarket 10 Video Killed the Radio Star 65
CSCO 15 CISCO Systems NULL
remarket 55 It's the shoes, Money! 65



Go to Top of Page
   

- Advertisement -