Solved

SQL Query - SUM Two Columns in One Row

Posted on 2013-06-06
10
582 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Efficient way to get backups off site to Azure

This user guide provides instructions on how to deploy and configure both a StoneFly Scale Out NAS Enterprise Cloud Drive virtual machine and Veeam Cloud Connect in the Microsoft Azure 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
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…

752 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