I have a query similar to the following:
SELECT CASE WHEN (GROUPING(Name) = 1) THEN 'All' ELSE Name END AS Name,
CASE WHEN (GROUPING(Type) = 1) THEN 'All' ELSE Type END AS Type,
sum(quantity) AS [Quantity],
CAST(sum(quantity) * (SELECT QuantityMultiplier FROM QuantityMultipliers WHERE a = t.b) AS DECIMAL(18,2)) AS Multiplied Quantity
FROM @Table t
GROUP BY Name, Type WITH ROLLUP
I’m trying to return a list of Names, Types, a summed Quantity and a summed quantity multiplied by an arbitrary number. All fine so far. I also need to return a sub-total row per Name and per Type, such as the following
Name Type Quantity Multiplied Quantity
------- --------- ----------- -------------------
a 1 2 4
a 2 3 3
a ALL 5 7
b 1 6 12
b 2 1 1
b ALL 7 13
ALL ALL 24 40
The first 3 columns are fine. I’m getting null values in the rollup rows for the multiplied quantity though. The only reason I can think this is happening is because SQL doesn’t recognize the last column as an aggregate now that I’ve multiplied it by something.
Can I somehow work around this without things getting too convoluted?
I will be falling back onto temporary tables if this can’t be done.
In your sub-query to acquire the multiplier, you have
WHERE a=b. Are eitheraorbfrom the tables in your main query?If these values are static (nothing to do with the main query), it looks like it should be fine…
If the
aorbvalues are thenameortypefield, they can beNULLfor the rollup records. If so, you can change to something similiar to…CAST(sum(quantity * (<multiplie_query>)) AS DECIMAL(18,2)).If
aorbare other field from your main query, you’d be getting multiple records back, not just a single multiplier. You could change to something like…CAST(sum(quantity) * (SELECT MAX(multiplier) FROM ...)) AS DECIMAL(18,2))