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
 Help with an If/Else

Author  Topic 

Apples
Posting Yak Master

146 Posts

Posted - 2008-04-24 : 15:38:51
I haven't written any code yet, I'm a little confused about it. Here's my tables:

----------------------------------------
Members
----------------------------------------
ID | FirstName | LastName
----------------------------------------


----------------------------------------
Donors
----------------------------------------
ID | DonateTo | Amount
----------------------------------------


Donors have the option of donating to a certain member, or donating to the company overall. If DonateTo is null, that means they donate to the company overall, and if contains an ID, that's the ID of the member they want to donate to.

I'd like to select all the donations in Donors. If DonateTo is null, I want to output 'None'. If there is an ID in DonateTo, I'd like to output the first name and last name of the member being donated to.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-04-24 : 15:54:59
[code]SELECT FirstName, LastName, SUM(Amount)
FROM (
SELECT m.ID, m.FirstName, m.LastName, d.Amount
FROM Members AS m INNER JOIN Donors AS d ON d.DonateTo = m.ID

UNION ALL

SELECT NULL, 'None', '', Amount
FROM Donors WHERE DonateTo IS NULL
) AS d
GROUP BY ID, FirstName, LastName[/code]or this[code]SELECT COALESCE(m.FirstName + ' ' m.LastName, 'Done'), SUM(d.Amount)
FROM Donors AS d
LEFT JOIN Members AS m ON m.ID = d.DonateTo
GROUP BY COALESCE(m.FirstName + ' ' m.LastName, 'Done')[/code]


E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page
   

- Advertisement -