SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 3 tables and a sum()
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Tim_Blanch
Starting Member

1 Posts

Posted - 08/20/2012 :  16:41:28  Show Profile  Reply with Quote
I have 3 tables
BillHeader with SupplierId, CustomerId
BillProperty with SupplierId
BillChg with CustomerId, CommFlg

with the query:
SELECT DISTINCT CustomerId, SUM(CASE WHEN CommFlg = 1 THEN 1 ELSE 0 END) AS ComFlag FROM BillChg
GROUP BY CustomerId
I get my CustomerId, ComFlag where ComFlag is the sum of all bool fields that are associated with CustomerId.
Now I would like(that I am having trouble with) to add my SupplierId that is associated with the CustomerId.
I have tried:
SELECT DISTINCT a.SupplierId, b.CustomerId, SUM(CASE WHEN c.CommFlg = 1 THEN 1 ELSE 0 END) AS ComFlag
FROM BillProperty a
JOIN BillHdr b ON a.SupplierId = b.SupplierId
JOIN BillChg c ON b.CustomerId = c.CustomerId
WHERE a.SupplierId = 745079813 AND c.CustomerId = 2277565
GROUP BY a.SupplierId, b.CustomerId, c.CommFlg
ORDER BY a.SupplierId
But no luck
I would like an output like:
SupplierId, CustomerId, Sum of CommFlg

Can anyone help me a little here?

Thanks

visakh16
Very Important crosS Applying yaK Herder

India
47189 Posts

Posted - 08/20/2012 :  16:51:33  Show Profile  Reply with Quote

SELECT a.SupplierId, b.CustomerId,c.ComFlag
FROM BillProperty a
JOIN BillHdr b ON a.SupplierId = b.SupplierId
JOIN(
SELECT CustomerId, SUM(CASE WHEN CommFlg = 1 THEN 1 ELSE 0 END) AS ComFlag 
FROM BillChg 
GROUP BY CustomerId
)c
ON b.CustomerId = c.CustomerId
WHERE a.SupplierId = 745079813 AND c.CustomerId = 2277565
ORDER BY a.SupplierId


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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.08 seconds. Powered By: Snitz Forums 2000