dbTalk Databases Forums  

Sum, count and divide

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Sum, count and divide in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Luciano \(DOC\)
 
Posts: n/a

Default Sum, count and divide - 10-28-2010 , 02:28 PM






I have a table having this structure:
idrecord
nation
value
What I have to get by a query is grouping records by nation, summing and
counting the values, dividing negative by positive.
Therefore:
USA, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
ITALY, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
FRANCE, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
I hope I was clear enough :-)
Thanks.

Luciano

Reply With Quote
  #2  
Old   
Hugo Kornelis
 
Posts: n/a

Default Re: Sum, count and divide - 10-28-2010 , 03:07 PM






Op 28-10-2010 21:28, Luciano (DOC) schreef:
Quote:
I have a table having this structure:
idrecord
nation
value
What I have to get by a query is grouping records by nation, summing and
counting the values, dividing negative by positive.
Therefore:
USA, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
ITALY, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
FRANCE, sumOfPositiveValues, CountOfPositiveValues, sumOfNegativeValues,
CountOfNegativeValues
I hope I was clear enough :-)
Thanks.

Luciano
Hi Luciano,

You can use something like this:

SELECT Nation,
SUM(CASE WHEN Value >= 0 THEN Value END),
COUNT(CASE WHEN Value >= 0 THEN Value END),
SUM(CASE WHEN Value < 0 THEN Value END),
COUNT(CASE WHEN Value < 0 THEN Value END)0
FROM YourTable
GROUP BY Nation;

(untested - for a tested reply, please see www.aspfaq.com/5006)


--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis

Reply With Quote
  #3  
Old   
Luciano \(DOC\)
 
Posts: n/a

Default Re: Sum, count and divide - 10-28-2010 , 03:32 PM



"Hugo Kornelis" <hugo (AT) perFact (DOT) REMOVETHIS.info.INVALID> ha scritto nel
messaggio news:8iu3fcFfn1U1 (AT) mid (DOT) individual.net...

Quote:
SELECT Nation,
SUM(CASE WHEN Value >= 0 THEN Value END),
COUNT(CASE WHEN Value >= 0 THEN Value END),
SUM(CASE WHEN Value < 0 THEN Value END),
COUNT(CASE WHEN Value < 0 THEN Value END)0
FROM YourTable
GROUP BY Nation;
Great, thank you very much!

Luciano

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.