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
 count result appear null

Author  Topic 

peace
Constraint Violating Yak Guru

420 Posts

Posted - 2013-08-26 : 04:01:26
MONTH Total Topic EndTotal
May 20 A 20
May 1000 B 2

how can i count topic='B' which is (20/1000) * 100
I get the result NULL

select *, case when topic='B' then SUM(case when topic='A' then Total end) / SUM(case when topic='B' then Total end) * 100 end
from tableA

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-08-26 : 04:39:28
[code]SELECT c1.*, CASE WHEN c1.Topic='B' THEN sums END
FROM @tab c1
LEFT JOIN (SELECT MONTHS, SUM(CASE WHEN Topic= 'A' THEN Total END)*100/SUM(CASE WHEN Topic= 'B' THEN Total END) Sums
FROM @tab
GROUP BY MONTHS
) c2
ON c1.MONTHS = c2.MONTHS[/code]

--
Chandu
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-27 : 01:42:26
how will Cout B be 20/1000? as i see you've 2 as Total for B

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2013-08-27 : 22:42:02
quote:
Originally posted by peace
select *, case when topic='B' then SUM(case when topic='A' then Total end) / SUM(case when topic='B' then Total end) * 100 end
from tableA


Highlighted text shows that the calculation was performed when topic = B, therefore when topic <> B, no calculation performed and no value return, therefore it return null.
Go to Top of Page
   

- Advertisement -