;WITH cte AS (
SELECT
EmployeeKey
, FirstName + ' ' + LastName EmployeeName
, ParentEmployeeKey
, 1 EmployeeLevel
, CAST(EmployeeKey as varchar(max)) as HierarchyPath
FROM dbo.DimEmployee
WHERE ParentEmployeeKey IS NULL
and EndDate IS NULL
UNION ALL
SELECT
c.EmployeeKey
, c.FirstName + ' ' + c.LastName
, c.ParentEmployeeKey
, p.EmployeeLevel + 1
, p.HierarchyPath + '\' + cast(c.EmployeeKey as varchar(max)) as HierarchyPath
FROM dbo.DimEmployee c
JOIN cte p ON p.EmployeeKey = c.ParentEmployeeKey
where EndDate IS NULL
)
SELECT
cte.EmployeeName
, cte.EmployeeLevel
, HierarchyPath
, cte.EmployeeKey
, cte.ParentEmployeeKey
, case when sum(isnull(f.SalesAmount,0)) <> 0 then cast(1 as bit) else cast(0 as bit) end as HasFactRecords
FROM cte
LEFT JOIN dbo.FactResellerSales f
ON f.EmployeeKey = cte.EmployeeKey
group by cte.EmployeeName, cte.EmployeeLevel , HierarchyPath , cte.EmployeeKey ,cte.ParentEmployeeKey
ORDER BY HierarchyPath, EmployeeName
Till Next Time
Showing posts with label PARENT CHILD. Show all posts
Showing posts with label PARENT CHILD. Show all posts
Wednesday, October 30, 2013
Tuesday, October 29, 2013
TSQL Parent Child
;WITH cte AS (
SELECT
EmployeeKey
, FirstName + ' ' + LastName EmployeeName
, ParentEmployeeKey
, 1 EmployeeLevel
FROM dbo.DimEmployee
WHERE ParentEmployeeKey IS NULL
UNION ALL
SELECT
c.EmployeeKey
, c.FirstName + ' ' + c.LastName
, c.ParentEmployeeKey
, p.EmployeeLevel + 1
FROM dbo.DimEmployee c
JOIN cte p ON p.EmployeeKey = c.ParentEmployeeKey
)
SELECT
REPLICATE('- ',cte.EmployeeLevel) + cte.EmployeeName
, cte.EmployeeLevel
, sum(ISNULL(f.SalesAmount, 0)) SalesAmount
FROM cte
LEFT JOIN dbo.FactResellerSales f
ON f.EmployeeKey = cte.EmployeeKey
group by cte.EmployeeName,cte.ParentEmployeeKey,cte.EmployeeLevel
ORDER BY EmployeeLevel, EmployeeName
Till Next Time
SELECT
EmployeeKey
, FirstName + ' ' + LastName EmployeeName
, ParentEmployeeKey
, 1 EmployeeLevel
FROM dbo.DimEmployee
WHERE ParentEmployeeKey IS NULL
UNION ALL
SELECT
c.EmployeeKey
, c.FirstName + ' ' + c.LastName
, c.ParentEmployeeKey
, p.EmployeeLevel + 1
FROM dbo.DimEmployee c
JOIN cte p ON p.EmployeeKey = c.ParentEmployeeKey
)
SELECT
REPLICATE('- ',cte.EmployeeLevel) + cte.EmployeeName
, cte.EmployeeLevel
, sum(ISNULL(f.SalesAmount, 0)) SalesAmount
FROM cte
LEFT JOIN dbo.FactResellerSales f
ON f.EmployeeKey = cte.EmployeeKey
group by cte.EmployeeName,cte.ParentEmployeeKey,cte.EmployeeLevel
ORDER BY EmployeeLevel, EmployeeName
Till Next Time
Subscribe to:
Posts (Atom)