Solved

SQL Query - SUM Two Columns in One Row

Posted on 2013-06-06
10
581 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

Suggested Solutions

Title # Comments Views Activity
Syntax issue with my Where Clause SQL 2012 20 38
SQL Query Syntax error after > 11 39
T-SQL to copy a database 37 66
Need help with a query 14 35
Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
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 ?
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

735 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