Tuesday, February 28, 2012

Common Table Expression(CTE) With Concept in Sql server.

CTE with multiple references

;with
cte_Orders
AS
(
    SELECT
        ID
        ,Description
        ,OrderDate
    FROM
        Orders
    WHERE
        OrderDate BETWEEN '2011-03-01' AND '2011-03-31'
)
,cte_OrderParts
AS
(
    SELECT
        SUM(UnitPrice * Quantity) AS Amount
        ,Order_ID
    FROM
        OrderParts
            INNER JOIN cte_Orders ON Order_ID = cte_Orders.ID
    GROUP BY
        Order_ID
)
,cte_OrderLabor
AS
(
    SELECT
         SUM(UnitPrice * Quantity) AS Amount
        ,Order_ID
    FROM
        OrderLabor
            INNER JOIN cte_Orders ON Order_ID = cte_Orders.ID
    GROUP BY
        Order_ID
)
SELECT
    ID
    ,Description
    ,OrderDate
    ,COALESCE(cte_OrderParts.Amount, 0.00) AS PartsAmount
    ,COALESCE(cte_OrderLabor.Amount, 0.00) AS LaborAmount
FROM
    cte_Orders
        LEFT JOIN cte_OrderParts ON ID = cte_OrderParts.Order_ID
        LEFT JOIN cte_OrderLabor ON ID = cte_OrderLabor.Order_ID

with ct (CityID,StateID,CityName) as
(
Select CityID,StateID,CityName
from City
)
,
st (StateID,StateName, regionID) as
(
Select StateID,StateName, regionid from state
)
,
rt (RegionID,RegionName) as
(
Select rr.RegionID,rr.RegionName from region rr
join st on st.RegionID = rr.RegionID
)
Select ct.CityName, st.StateName, rt.RegionName
From CT
join ST on ct.stateID = st.stateID
join rt on rt.RegionID = rt.RegionID

in above query the ST cte is being used twice.

_________________________________________________________________\

WITH

  cteTotalSales (SalesPersonID, NetSales)

  AS

  (

    SELECT SalesPersonID, ROUND(SUM(SubTotal), 2)

    FROM Sales.SalesOrderHeader

    WHERE SalesPersonID IS NOT NULL

    GROUP BY SalesPersonID

  )

SELECT

  sp.FirstName + ' ' + sp.LastName AS FullName,

  sp.City + ', ' + StateProvinceName AS Location,

  ts.NetSales

FROM Sales.vSalesPerson AS sp

  INNER JOIN cteTotalSales AS ts

    ON sp.BusinessEntityID = ts.SalesPersonID

ORDER BY ts.NetSales DESC

 

No comments:

Post a Comment