How many flashlights did John Gray buy?
This is the result I need to achieve:
So far I have this:
IF NOT (EXISTS (SELECT
c.[customerid],
c.[firstname],
c.[lastname],
cp.[quantity]
FROM [dbo].[customers] AS c
INNER JOIN [dbo].[Customer_Purchases] AS cp
ON c.[customerid] = cp.[customerid]
WHERE
c.[customerid] = 10101
AND cp.[item] = 'Flashlight'
GROUP BY
c.[customerid],
c.[firstname],
c.[lastname],
cp.[quantity]
)
)BEGIN
SELECT
c.[customerid] AS ID,
c.[firstname] AS First Name,
c.[lastname] AS Last Name,
'Flashlight' AS Item,
'0' As Quantity
FROM [dbo].[customers] AS c
WHERE
c.[customerid] = 10101
GROUP BY
c.[customerid],
c.[firstname],
c.[lastname]
END
What is the more practical approach?
I have gone trough several SO threads regarding issues of such (this, this, this and this), but the necessary JOIN
seems to be making it rather too complex for me.
Edit 1:
- Corrected inconsistencies in the code;
- Provided hyperlinks to SO threads.