Solved

SQL Query - SUM Two Columns in One Row

Posted on 2013-06-06
10
579 Views
Last Modified: 2013-06-06
Hello,

I have a question with MS SQL Query I am trying to write.

The table fields I am using are (there will be a few more e.g. matching CompanyID to another table for the CompanyName and EXTMins will also be used so I would add mins and hours together but hopefully this request can be written or some guidance I should be able to write the rest)
CostCode (nchar)
ExtHours (Int)
CompanyID (Int)

The table is called Timesheets.

The user can only enter RTI or NRT for Cost Code, ExtHour can be any integer and the CompanyID is matched to another table which for the moment is not important.

I want a query to
Total up the total of ExtHours for NRT and RTI and group by company. I want these answers in just one row for each company.

e.g. Company ID, Total for NRT, Total for RTI.

Now not all companies will have RTI but if there is no data I want it to be 0.

I have tried something very simple which is below.

SELECT        costcode, SUM(exthours) AS Expr1, CompanyId
FROM           Timesheets
GROUP BY costcode, CompanyId

Open in new window


This works to a limit but it does not group it how I want it.
I was thinking of a query which is like this

SELECT       costcode,( SELECT SUM(exthours) from Timesheets where costcode = 'RTI') as RTITotal, (SELECT SUM(extHours) from Timesheets where costCode = 'NRT') AS NRTTOtal, CompanyId
FROM            Timesheets
GROUP CompanyId

Open in new window


But that doesn't work, so any suggestions would be very useful.

Thanks,
Alex
0
Comment
Question by:BoltonWanderer
10 Comments
 
LVL 11

Expert Comment

by:Simone B
ID: 39226983
Try this:

SELECT       CompanyId,
CASE WHEN costcode = 'RTI' THEN SUM(exthours) END AS RTITotal,
CASE WHEN costcode = 'NRT' THEN SUM(exthours) END AS NRTTotal
 
FROM            Timesheets
GROUP BY CompanyId

Open in new window

0
 
LVL 11

Expert Comment

by:Guru Ji
ID: 39226989
Try this

SELECT        costcode, CASE WHEN costcode = 'RTI' OR costcode = 'NRT' THEN SUM(exthours) ELSE 0 END as TotalSum , CompanyId
FROM           Timesheets
GROUP BY CompanyId, costcode

Open in new window


If you don't want costcode then

SELECT         CompanyId, CASE WHEN costcode = 'RTI' OR costcode = 'NRT' THEN SUM(exthours) ELSE 0 END as TotalSum 
FROM           Timesheets
GROUP BY CompanyId

Open in new window

0
 
LVL 11

Expert Comment

by:Simone B
ID: 39227012
Sorry, I forgot about this - "Now not all companies will have RTI but if there is no data I want it to be 0."

SELECT       CompanyId,
CASE WHEN costcode = 'RTI' THEN SUM(ISNULL(exthours,0)) END AS RTITotal,
CASE WHEN costcode = 'NRT' THEN SUM(ISNULL(exthours,0)) END AS NRTTotal
 
FROM            Timesheets
GROUP BY CompanyId 

Open in new window

0
NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

 

Author Comment

by:BoltonWanderer
ID: 39227014
@Buttercup1 that is what I want I believe however I get a message saying

Executed SQL statement: SELECT CompanyId, CASE WHEN costcode = 'RTI' THEN SUM(exthours) END AS RTITotal, CASE WHEN costcode = 'NRT' THEN SUM(exthours) END AS NRTTotal FROM dbo.Timesheets GROUP BY CompanyId
Error Source: .Net SqlClient Data Provider
Error Message: Column 'dbo.Timesheets.costcode' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Sorry @write2mohit that just groups the total and on different rows or it puts it on one row but its either this or that. what I would like to archieve is to have CompanyID, TotalExtHours which is NRT, TotalExtHours which is RTI on a per row basis.

Thanks,
0
 
LVL 11

Accepted Solution

by:
Simone B earned 500 total points
ID: 39227045
Oops, sorry. The problem with adding costcode to the GROUP BY clause is that you're back to 2 lines for each CompanyID again. You can use CTE, or use a subquery as below. This seems repetitive, but should give you what you need:

SELECT X.CompanyID, SUM(X.RTITotal) RTITotal, SUM(X.NRTTotal) NRTTotal
FROM (

SELECT       CompanyId,
CASE WHEN costcode = 'RTI' THEN SUM(ISNULL(exthours,0)) END AS RTITotal,
CASE WHEN costcode = 'NRT' THEN SUM(ISNULL(exthours,0)) END AS NRTTotal
 
FROM            Timesheets
GROUP BY CompanyId, costcode
) X
GROUP BY CompanyID

Open in new window

0
 

Author Comment

by:BoltonWanderer
ID: 39227053
@Buttercup1 Thank You. Just what I needed :)
0
 
LVL 11

Expert Comment

by:Simone B
ID: 39227079
You're welcome!
0
 
LVL 11

Expert Comment

by:Simone B
ID: 39227247
Can you assign points?
tx
0
 

Author Closing Comment

by:BoltonWanderer
ID: 39227256
Just what I wanted. Thanks.
0
 
LVL 48

Expert Comment

by:PortletPaul
ID: 39228009
btw:

SELECT
      CompanyId
    , SUM(CASE WHEN costcode = 'RTI' THEN exthours ELSE 0 END) AS RTITotal
    , SUM(CASE WHEN costcode = 'NRT' THEN exthours ELSE 0 END) AS NRTTotal
FROM Timesheets
GROUP BY CompanyId

-- no need for an inner subquery, it's where you put the SUM( ... ) that matters
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
In this article we will learn how to fix  “Cannot install SQL Server 2014 Service Pack 2: Unable to install windows installer msi file” error ?
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question