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 |
Leigh79
Starting Member
28 Posts |
Posted - 2008-03-05 : 09:17:24
|
Hi GuysI was hoping someone could help me?I have the following SELECT statement:SELECT branchno AS Dept, SUM(adults) AS Adults, SUM(children) AS Kids, SUM(pax) AS Pax, SUM(grossprofit) AS Comm, SUM(tar_saleprice) AS TotalCost, SUM(CASE WHEN suboperator = 'DISCAT' OR suboperator = 'DISCNA' THEN grossprofit ELSE 0 END) AS Discount, (SUM(grossprofit)/(SUM(saleprice)+SUM(CASE WHEN suboperator = 'DISCAT' OR suboperator = 'DISCNA' THEN grossprofit ELSE 0 END)))*100 AS CommPercWhich gives me the following results:Branch1 | 2 | 2 | 4 | 205.00 | 2585.00 | -142.00 | 8.39%This is fine when as in the example above the 'Comm' is higher than 0 however when it is a 0 value I get an error when trying to divide the result to provide the column CommPerc. I want to be able to check if the 'Comm' column <> 0 and if it isn't then go ahead with the calculation otherwise return a zero value.Any ideas?PS. Sorry if this doesn't seem clear... |
|
harsh_athalye
Master Smack Fu Yak Hacker
5581 Posts |
Posted - 2008-03-05 : 09:22:41
|
Make use of derived table.Something like this:select ...,somecol/case when comm = 0 then 1 else comm end as somecol,...from(select ...,SUM(grossprofit) AS Comm,...from ...) t Harsh AthalyeIndia."The IMPOSSIBLE is often UNTRIED" |
 |
|
madhivanan
Premature Yak Congratulator
22864 Posts |
Posted - 2008-03-05 : 09:24:31
|
or if you want null, thensomecol/nullif(comm,0)MadhivananFailing to plan is Planning to fail |
 |
|
jsmith8858
Dr. Cross Join
7423 Posts |
|
Leigh79
Starting Member
28 Posts |
Posted - 2008-03-05 : 09:44:53
|
Hi GuysThanks for you help, I've now got this working!The new query is:SELECT tar_branchno, SUM(tar_adults) AS Adults, SUM(tar_children) AS Kids, SUM(tar_pax) AS Pax, SUM(tar_grossprofit) AS Comm, SUM(tar_saleprice) AS SalePrice, SUM(tar_disc) AS Disc, CASE WHEN SUM(tar_grossprofit) = 0 THEN 0 ELSE (SUM(tar_grossprofit)/(SUM(tar_saleprice)+SUM(tar_disc)))*100 END AS Perc FROM(SELECT tar_branchno, tar_adults, tar_children, tar_pax, tar_grossprofit, tar_saleprice, CASE WHEN tar_suboperator = 'DISCAT' OR tar_suboperator = 'DISCNA' THEN tar_grossprofit ELSE 0 END AS tar_discFROM tar_downloads_newWHERE tar_transactiondate = '29/01/2008' AND tar_booked = '29/01/2008')tblGROUP BY tbl.tar_branchno |
 |
|
|
|
|
|
|