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
 How to have aggregate with 2 condition in query

Author  Topic 

Sambasivam
Starting Member

36 Posts

Posted - 2008-11-25 : 11:59:37
I have 2 tables linked as

Table A
=======
Field1 - (FK to Table B)
Field2 - (Integer value)

Table B
=======
Field1 - Id (PK)
Field2 - Name(x,y,z)

I have these data in Table A
=============================
Field1 Field2
1 10
1 5
2 7
3 6

Table B Data
============
Field1 Field2
1 X
2 Y
3 Z

Now I need a query which will have aggregate SUM of Table A.Field2 for all id in TableB and aggregate SUM of Table A.Field2 for all id in TableB except id 2 as

SELECT SUM (Table A.Field2) for all id of Table B,
SUM (Table A.Field2) for all id of Table B except id 2

FROM Table A, TableB
WHERE .......

Is it possible to have it in single query? If so how can we do it? Please help me.




visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-25 : 12:04:58
[code]SELECT
SUM (a.Field2) AS Toatl,
SUM (CASE WHEN b.Field1<> 2 THEN a.Field2 ELSE 0 END) AS Total2
FROM TableA a
JOIN TableB b
ON a.Field1=b.Field1
[/code]
Go to Top of Page

Sambasivam
Starting Member

36 Posts

Posted - 2008-11-25 : 12:11:08
Thank You. It worked perfectly as I wanted. Im very very delighted with your help.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-11-25 : 12:14:49
You're welcome
Go to Top of Page
   

- Advertisement -