I have this query, which works perfectly when I supply the retailer_id parameter with a value.
SELECT reda.RetailerId,
( SELECT SUM(reda.Purchases)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS Purchases,
( SELECT SUM(reda.PurchaseTotal)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS PaymentsTotal,
( SELECT SUM(reda.Refunds)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS Refunds,
( SELECT SUM(reda.RefundTotal)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS RefundsTotal,
( SELECT SUM(reda.OffersOptedInto)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS OffersOptedInto,
( SELECT SUM(reda.RedeemedOffers)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS RedeemedOffers,
( SELECT SUM(reda.RedeemedOfferTotal)
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId) AS RedeemedOfferTotal
FROM RetailerDaily reda
WHERE (reda.RetailerId = @retailer_id
OR @retailer_id IS NULL)
AND (reda.DateStart >= @date_from
OR @date_from IS NULL)
AND (reda.DateStart <= @date_to
OR @date_to IS NULL)
GROUP BY reda.RetailerId
However, when I pass in retailer_id as null I receive the following error message
Msg 512, Level 16, State 1, Line 9
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
Can anybody shed some light onto how to resolve this issue as I can’t seem to work it out.
Thanks in advance
Steven
As commented before, this is expected behavior. You are using subqueries as expressions, and they are only allowed to return a single value. If you pass in NULL, they will produce multiple values.
Why on Earth are you even using so many subqueries? Your query could be simplified as follows: