Skip to content
Advertisement

How to go convert to CTE

I am a little confused out a CTE works. I need to convert my statement from a rollup with a UNION to a CTE… but the CTE is a bit confusing me.

Any Ideas how to approach this?

SELECT
    ProductName,
    Sum ((ItemPrice - DiscountAmount)*Quantity) as ProductTotal
FROM
    Products 
 JOIN OrderItems 
ON Products.ProductID = OrderItems.productID

GROUP BY ProductName WITH ROLLUP

Order By ProductTotal

Advertisement

Answer

You can express this using a CTE as:

with cte as (
      select ProductName,
             Sum((ItemPrice - DiscountAmount)*Quantity) as ProductTotal
      from Products p join
           OrderItems oi
           on p.ProductID = oi.productID
      group by ProductName
     )
select *
from cte
union all
select null, sum(producttotal)
from cte
order by producttotal;
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement