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 2008 Forums
 Transact-SQL (2008)
 Interesting Group By Need

Author  Topic 

qman
Constraint Violating Yak Guru

442 Posts

Posted - 2011-10-25 : 08:02:53
I am trying to insert grouped records into a TEMP table based on a condition of one of the tables columns. If the same column does not = a specific value, insert records NON GROUPED into the SAME TEMP table. Pseudo code below....

-- If column A is 1, group records and add them to temp table.
-- I only want one "grouped" record added to the temp table
-- if column A is 1. Otherwise, it is assumed column A is 0,
-- and treat those records normal, adding them to the
-- SAME temp table (non grouped).
if a is 1
select a, b, c, d, e, f into #TEST from MAIN_TABLE
group by a
else
select a, b, c, d, e, f into #TEST from MAIN_TABLE

AndrewMurphy
Master Smack Fu Yak Hacker

2916 Posts

Posted - 2011-10-25 : 08:38:29
group by implies aggregation is summing, averaging etc.
what do you want to do with b,c ,d, e , ...are these numeric values?
or do you just want unique values?

insert into #TEST
select a, sum(b), sum(c), sum(d), sum(e), sum(f)
from MAIN_TABLE
where a = 1
group by a
union all
select a, b, c, d, e, f
from MAIN_TABLE
where a <> 1


or

insert into #TEST
select distinct a, b, c, d, e, f
from MAIN_TABLE
where a = 1
union all
select a, b, c, d, e, f
from MAIN_TABLE
where a <> 1
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-10-26 : 01:11:44
is column a is nullable make sure you add some modification below in case you need null valued records also


insert into #TEST
select distinct a, b, c, d, e, f
from MAIN_TABLE
where a = 1
union all
select a, b, c, d, e, f
from MAIN_TABLE
where a <> 1
or a is null


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -