Solved

SQL Query - SUM Two Columns in One Row

Posted on 2013-06-06
10
569 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:BoltonWanderer
Comment Utility
@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
Comment Utility
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
Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 

Author Comment

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

Expert Comment

by:Simone B
Comment Utility
You're welcome!
0
 
LVL 11

Expert Comment

by:Simone B
Comment Utility
Can you assign points?
tx
0
 

Author Closing Comment

by:BoltonWanderer
Comment Utility
Just what I wanted. Thanks.
0
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
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 Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

Join & Write a Comment

Suggested Solutions

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now