Question

Calculate Two Columns

Asked by: RecipeDan

Hello:

I am trying to calculate two columns that are nvarchar(50) using this statement

SELECT AName, CAST(Count(TotalA) AS INT)/CAST(Count(TotalB) AS INT)*100 AS GrandTotal FROM DATA

In the GrandTotal Column 0 is shown for the caculation. However when I use +, -, or * expressions both columns are calculated and a result is shown

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-09 at 18:43:56ID24800998
Tags

MS SQL Server 2005

Topic

MS SQL Server

Participating Experts
6
Points
500
Comments
24

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. How to calculate SUBTOTALS and GRANDTOTALS for an E…
    Let's say I have a spreadsheet that I refence in Access in the following way in 1 of my sup procedures: Private Sub StartDocInternalXLS(filename) Dim xlApp As Excel.Application Dim xlWB As Excel.Workbook Dim xlWS As Excel.Worksheet 'open excel template Set xlApp = New E...
  2. PayPal grandtotal field
    I have a shopping cart I wish to connect to PayPal. I have a checkout page which is showing Sub Total 100 Post and Packing 10 Grand Total 110 Thats all OK Transfering the code to PayPal if have this code in the page. Most fields get passed OK <input type="hidd...
  3. Peristed Data in calculated datetime column (nvarchar to d…
    I am having trouble getting SQL 2005 to let me setup a persisted data field. Here is what I have (it really sucks, but I have to deal with it as is....unfortunately). SQL Table as Follows (snippet) Date_of_Record_Year -> varchar(2) Date_of_Record_Month -> varchar(2) ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: leakim971Posted on 2009-10-09 at 18:48:38ID: 25540303

Hello RecipeDan,

Try :

SELECT AName, CAST(Count(TotalA) AS DECIMAL(10,2))/CAST(Count(TotalB) AS DECIMAL(10,2))*100 AS GrandTotal FROM DATA 
or  
SELECT AName, Count(CAST(TotalA AS DECIMAL(10,2)))/Count(CAST(TotalB) AS DECIMAL(10,2)))*100 AS GrandTotal FROM DATA
                                              
1:
2:
3:
4:
5:

Select allOpen in new window

 

by: RecipeDanPosted on 2009-10-09 at 18:56:01ID: 25540333

That gives me a value of 100 then when I drop the *100 I get a value of 1

 

by: leakim971Posted on 2009-10-09 at 19:08:26ID: 25540380

Try this :

SELECT AName, CAST(Count(TotalA) AS DECIMAL(10,2))/(CAST(Count(TotalB) AS DECIMAL(10,2))*100) AS GrandTotal FROM DATA

                                              
1:

Select allOpen in new window

 

by: MuhammadKashifPosted on 2009-10-09 at 19:11:01ID: 25540389

try this query

SELECT AName, (Count(CAST(TotalA AS INT))/Count(CAST(TotalB AS INT)))*100 AS GrandTotal FROM DATA

 

by: leakim971Posted on 2009-10-09 at 19:11:16ID: 25540390

You shoud get 0.01

Are you sure you want to count number of non null value from TotalA and TotalB and not doing the sum of TotalA and sum of TotalB ?

In this case :


SELECT AName, Sum(CAST(TotalA AS DECIMAL(10,2)))/(Sum(CAST(TotalB) AS DECIMAL(10,2)))*100) AS GrandTotal FROM DATA
                                              
1:

Select allOpen in new window

 

by: MuhammadKashifPosted on 2009-10-09 at 19:17:34ID: 25540416

if you want sum then use following

SELECT AName, (sum(CAST(TotalA AS INT))/sum(CAST(TotalB AS INT)))*100 AS GrandTotal FROM DATA
group by AName

 

by: acperkinsPosted on 2009-10-09 at 19:18:36ID: 25540420

>>That gives me a value of 100 then when I drop the *100 I get a value of 1<<
As it should.  Unless there are Nulls Count(TotalA) = Count(TotalB)

 

by: RiteshShahPosted on 2009-10-09 at 20:50:18ID: 25540758

this may help:

SELECT AName, CAST(Count(isnull(TotalA,0)) AS INT)/CAST(Count(isnull(TotalB,0)) AS INT)*100 AS GrandTotal FROM DATA

 

by: RecipeDanPosted on 2009-10-09 at 21:47:10ID: 25540887

No matter which one I try I get a cannnot convert nvarchar to numeric error message

 

by: RiteshShahPosted on 2009-10-09 at 21:59:15ID: 25540909

what error message do you get? I just created sample data and working fine, look at that.


create table DATA
(
TotalA nvarchar(20),
TotalB nvarchar(20)
)
 
insert into DATA
select null,'10' union all
select '20','10' union all
select '18',null union all
select null,null
 
 SELECT CAST(Count(isnull(TotalA,0)) AS INT)/CAST(Count(isnull(TotalB,0)) AS INT)*100 AS GrandTotal FROM DATA
 

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: mwvisa1Posted on 2009-10-09 at 22:03:44ID: 25540913

You need to combine the suggestions.

The ISNULL() recommendation was trying to get rid of NULLs from the count which since you are counting over same rows with no conditional will result in same count in the numerator and denominator; hence, 1 is always result.  So ADD conditional (CASE) statement.

To make this work, a good approach is to use SUM() versus COUNT().

e.g., SUM( CASE WHEN TotalA IS NOT NULL THEN 1 ELSE 0 END )
SUM( CASE WHEN TotalA IS NOT NULL THEN 1 END ) also works...

The conversion / casting to decimal removes the issue of integer division in SQL.  However, you can overcome this by multiplying by 1.0 also.  Whenever I am dealing with percentages or anything that I multiply by 100 later I usally take advantage of that and just do that in the numerator.

Here is what I mean all together :

SELECT AName
    , SUM( CASE WHEN TotalA IS NOT NULL THEN 1 END ) * 100.0 / SUM( CASE WHEN TotalB IS NOT NULL THEN 1 END ) AS GrandTotal
FROM
DATA

GROUP BY AName
;

And taking into consideration division by zero, you can do this :

SELECT AName
    ,  CASE B WHEN 0 THEN 0 ELSE A * 100.0 / B END AS GrandTotal
FROM (
   SELECT AName
        , SUM( CASE WHEN TotalA IS NOT NULL THEN 1 END ) AS A
        , SUM( CASE WHEN TotalB IS NOT NULL THEN 1 END ) AS B
   FROM DATA
   GROUP BY AName
)  derived
;


Hope that helps.

 

by: mwvisa1Posted on 2009-10-09 at 22:17:36ID: 25540924

And actually, the aggregates should be filtering NULLs, so you probably have empty strings instead of NULLs.

SELECT AName
    ,  CASE B WHEN 0 THEN 0 ELSE A * 100.0 / B END AS GrandTotal
FROM (
   SELECT AName
        , SUM( CASE WHEN NULLIF(TotalA, '') IS NOT NULL THEN 1 END ) AS A
        , SUM( CASE WHEN NULLIF(TotalB, '') IS NOT NULL THEN 1 END ) AS B
   FROM DATA
   GROUP BY AName
)  derived
;


Above uses NULLIF to force '' to NULL so we can evaluate NULLs and '' the same.

 

by: mwvisa1Posted on 2009-10-09 at 22:25:06ID: 25540941

Sorry it must be late, one last one.  As others have posted, it should work with very simple COUNT() so this should also work :

SELECT AName
    ,  CASE B WHEN 0 THEN 0 ELSE A * 100.0 / B END AS GrandTotal
FROM (
   SELECT AName
        , COUNT( NULLIF(TotalA, '') ) AS A
        , COUNT( NULLIF(TotalB, '') ) AS B
   FROM DATA
   GROUP BY AName
)  derived
;

 

by: RecipeDanPosted on 2009-10-09 at 22:27:17ID: 25540948

Here is my Database Structure. The GrandTotal Column is still not calculating properly. I still do not understand why if I use +, -, or * that it calculates the column

AName nvarchar(50)
TotalB nvarchar(50)
TotalA nvarchar(50)

AName        TotalA            TotalB
DAN             20      12
JOHN            20      10
DAN             18      8
DAN             50      30
JOHN            100      75

 

by: MuhammadKashifPosted on 2009-10-09 at 22:35:43ID: 25540963

have you tried this query

SELECT AName, (sum(CAST(TotalA AS INT))/sum(CAST(TotalB AS INT)))*100 AS GrandTotal FROM DATA
group by AName


or tell me your desired output.

 

by: mwvisa1Posted on 2009-10-09 at 22:36:21ID: 25540964

Are you trying to actually use the values as numbers?

When you use +, -, or * an implicit cast has to occur and would work if the data is always numeric.

Are you actually looking for this result :

208 * 100.0 / 135 = 154.07


 

by: dbbishopPosted on 2009-10-09 at 22:41:19ID: 25540969

I suspect you may have some values in TotalA and/or TotalB that are not able to be cast to numeric (i.e. Apha characters). Try this:

SELECT AName, SUM(CAST(CASE WHEN ISNUMERIC(TotalA) THEN TotalA ELSE 0 END AS DECIMAL(10,2))) /
             SUM(CAST(CASE WHEN ISNUMERIC(TotalB) THEN TotalB ELSE 0 END AS DECIMAL(10,2))) * 100 AS GrandTotal
FROM DATA

 

by: RecipeDanPosted on 2009-10-09 at 23:01:58ID: 25541004

This is an example of my desired output

AName      TotalA      TotalB      GrandTotal
Dan      20      12      60
John      20      14      70
Dan      18      7      38.89
Dan      50      40      80
John      70      25      35.71

Column TotalA will have Yes Values and Column TotalB will have No Values. I trying to count them and get a score

 

by: mwvisa1Posted on 2009-10-09 at 23:06:49ID: 25541012

Are you already showing us the grouped data by AName?

You indicate you want to count them and get a score, but the results appear to be percentage of B to A which is reverse of what showed earlier by the way.  Unless you have a type-o in the column headers above.

Select AName, TotalA, TotalB, TotalB * 100.0 / TotalA As Grandtotal
From DATA
;

Should give you the results above starting from data structure you gave.  Therefore, the COUNT() you were previously using leads me to believe the raw data is different, but maybe you simply need what I just posted.

 

by: mwvisa1Posted on 2009-10-09 at 23:16:17ID: 25541029

And don't forget you have to convert the columns to numeric data type for the calculation to work, but in essence what I shown is what you are doing (i.e., dividing B by A and multiplying by 100 instead of the other way around).

 

by: RecipeDanPosted on 2009-10-10 at 05:59:13ID: 25542142

mwvista1: I am not sure what you mean. My raw data isnt any different then what I originally posted. My last post was an example in response to MuhammadKashif. Maybe my example was not clear.

I have about 200 rows of yes values in TotalA and no values in TotalB. No null values in either column. I want to count them and divide TotalA by TotalB then multiply it by 100 to get a percentage score; which is the grand total column. Does my example make sense?

 

by: mwvisa1Posted on 2009-10-10 at 10:52:22ID: 25543067

Definitely not clear and didn't see any original posting.  Just what you last did which showed integer values in the columns and the desired output of :

AName      TotalA      TotalB      GrandTotal
Dan      20      12      60

Makes me think you need 12 / 20 which is 3 / 5 OR 60%.

"I have about 200 rows of yes values in TotalA and no values in TotalB. No null values in either column. I want to count them and divide TotalA by TotalB then multiply it by 100 to get a percentage score; which is the grand total column."

If you have 200 rows of each value with NO null values; then, when you count each column, you will and should get 200.  Subsequently, 200 / 200 OR x / x will always be 1.

So again, there must be something else you need to do the calculation appropriately, so it would be best if you actually showed a sample of the raw data and we can construct the query that may help.

Regards,

Kevin

 

by: RecipeDanPosted on 2009-10-12 at 23:05:29ID: 25557268

Hello:

OK. I figured out part of the problem, the data was imported into the database wrong. It makes sense that every calculation would be 1. Anyway, I am still having problems calculating the columns. With the new data Column TotalA will have a combination of yes no and maybe responses and column TotalB will have all yes responses. I still need to divide column TotalB by TotalA where TotalA = 'Yes' to get a total.
Sorry for the confusion I was concentrating more on than the sql statement than the actual data in the database.

 

by: mwvisa1Posted on 2009-10-13 at 00:17:14ID: 25557609

That makes a little more sense.

Select AName, A, B
    , A * 100.0 / B As GrandTotal
From (
  Select AName
       , Count(Case TotalA When 'Yes' Then 1 End) As A
       , Count(TotalB) As B
  From DATA
  Group By AName
) derived
;


Since TotalA is the column that has conditional and your previous post on expected results, I showed with TotalB (total rows) as the denominator; however, if you truly want TotalB / TotalA to get grand total then just switch those values around.  Since A is based on a conditional, then I would add in the "Case A When 0 Then 0 Else ... End" syntax shown previously to prevent divide by 0 errors which can occur when no records in TotalA column equal 'Yes'.

Hope that helps.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...