I have following table
AccountID Name
1 Foo Bar
2 Jon Dow
AccountID AddressLine City
1 123 Test RD New York
1 456 Test RD New York
2 Lombard Street San Francisco
2 Lombard Street San Francisco
For given AccountID i want to select AddressLine and City.
If the Account has same AddressLine then it should select that AddressLine value else return 'Multiple'.
If the Account has same City then it should select that City value else return 'Multiple'.
So for example for the account ID 1 the query should return
AccountID AddressLine City
1 Multiple New York
Here is SQLFiddle
Below is my query ( Not working). I think the issue is grouping and selecting count from sub squery
SELECT
A.AccountID,
CASE
WHEN T1.CNT = 1
THEN T1.AddressLine
ELSE 'Multiple'
END AS 'Address Line',
CASE WHEN T2.CNT = 1
THEN T2.City
ELSE 'Multiple'
END AS 'City'
FROM Accounts A
INNER JOIN
(
SELECT
ad.AccountID,
COUNT(DISTINCT(ad.AccountID)) AS CNT,
ad.AddressLine
FROM Addresses ad
GROUP BY ad.AccountID, ad.AddressLine
) T1 ON T1.AccountID = A.AccountID
INNER JOIN
(
SELECT
ad.AccountID,
COUNT(DISTINCT(ad.AccountID)) AS CNT,
ad.City
FROM Addresses ad
GROUP BY ad.AccountID, ad.City
) T2
ON T2.AccountID = A.AccountID
WHERE
a.AccountID = 1