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
 General SQL Server Forums
 New to SQL Server Programming
 How to Pursue if-elseif in SQL

Author  Topic 

goligol
Posting Yak Master

128 Posts

Posted - 2011-06-10 : 10:49:31
I would like to select from a table in the same slection command for two condition:
Select a if c=d and select b if c=e,

My actula code is:
SELECT O,D,M,C,avg(TM0) FROM dev.GAMS_Init_Var where TM0 is not null
and T0 <> 999999 group by O,D,M,C
(here I want to add the else part in the same command which is::::: SELECT O,D,M,C,MAX(TM0)FROM dev.GAMS_Init_Var where TM0 is not null and T0 = 999999 group by O,D,M,C)

Thank you

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2011-06-10 : 11:02:22
SELECT O,
D,
M,
C,
AVG(CASE WHEN ( TM0 is not null )
AND ( T0 <> 999999 ) THEN TM0
ELSE NULL
END) AVG_TMO,
SUM(CASE WHEN ( TM0 is not null )
AND ( T0 = 999999 ) THEN TM0
ELSE 0
END) MAX_TMO
FROM dev.GAMS_Init_Var
group by O,
D,
M,
C

--------------------------
http://connectsql.com/
Go to Top of Page

goligol
Posting Yak Master

128 Posts

Posted - 2011-06-10 : 11:14:17
Thank you.
Go to Top of Page

goligol
Posting Yak Master

128 Posts

Posted - 2011-06-10 : 12:15:22
The above command lines are working but the problem is I do not want to have two Columns (AVG_TM0) and (MAX_TM0).
I want one column simple TM0, where in this column put avg(TM0) [if TM0 not null and T0 <> 999999 groubby O,D,M,C] [elseif TM0 not null and T0 =999999 groubby O,D,M,C] max(Tm0).
It should automatically truncate the table.
In the above case it keeps all rows.

Thank you
Go to Top of Page
   

- Advertisement -