Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Summing in Select

Author  Topic 

bd528
Starting Member

23 Posts

Posted - 2011-08-26 : 10:07:08
Hi,

I have a query which returns invoices for accouts :-

SELECT accountno, totalcost
FROM invoice
WHERE invoice.invoicedatefrom = '2011-05-01 00:00:00.000'

What I'd like to do is have an additional column to display the combined total cost for all invoices between 2 dates, as well as the column for the specific date above.

Can anyone suggest a way to do this?

Thanks!

(I only have read access from the server/database)


visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-26 : 10:11:59
[code]SELECT accountno,
SUM( CASE WHEN invoice.invoicedatefrom = '2011-05-01 00:00:00.000' THEN totalcost ELSE 0 END) AS totalcost,
SUM( CASE WHEN invoice.invoicedatefrom BETWEEN @Date1 AND @Date2 THEN totalcost ELSE 0 END) AS totalcostbwdates
FROM invoice
GROUP BY accountno
[/code]
@Date1 and @Date2 are two date values

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

bd528
Starting Member

23 Posts

Posted - 2011-08-26 : 10:36:31
Exactly what I needed. Thank you!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-26 : 10:50:42
welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-08-29 : 03:44:01
Also try to use unambigious date format
http://beyondrelational.com/blogs/madhivanan/archive/2010/06/03/understanding-datetime-column-part-ii.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -