我最近下载了的AdventureWorks2012,并在网上发现了一些有关数据库的问题。我真的被困在一个,迫切需要一些指导;
展示从鲁思·埃勒布罗克到首席执行官肯·桑切斯的管理阶层
组织中的每个人在层次结构中都有一个OrganizationalLevel;首席执行官是0、副总裁1、工程经理2、高级工具设计人员3,并且逐渐下降。最低的是4。
我在做什么:,我要把[Person].[Person]和[HumanResources].[Employee]这两张表连接在一起,以获得FirstName, LastName,JobTitle, OrganizationalLevel
Select [Person].[Person].FirstName
, [Person].[Person].LastName
, [HumanResources].[Employee].OrganizationLevel
from [HumanResources].[Employee]
JOIN person.person ON ([HumanResources].[Employee].[BusinessEntityID]=[Person].[Person].[BusinessEntityID])据我理解,我需要使用递归查询或通用表表达式,但我真的不知道如何使用。
任何帮助都是非常感谢的。更多细节请随时提问。
谢谢。
发布于 2014-02-19 07:37:28
AdventureWorks示例的工作方式是在Employee表上使用HierarchyId数据类型--您真的不需要递归CTE --常规的CTE就可以了。
试着做这样的事情:
-- define the CTE to get the "anchor" data - the row for Ruth Ellerbrook
;WITH Anchor AS
(
SELECT
p.FirstName ,
p.LastName ,
e.OrganizationLevel,
e.OrganizationNode
FROM
HumanResources.Employee e
INNER JOIN
person.person p ON e.BusinessEntityID = p.BusinessEntityID
WHERE
p.FirstName = 'Ruth'
AND p.LastName = 'Ellerbrock'
)
SELECT
p.FirstName,
p.LastName,
e.OrganizationLevel,
CAST(e.OrganizationNode AS VARCHAR(20)) AS 'OrgNodeString'
FROM
HumanResources.Employee e
INNER JOIN
person.person p ON e.BusinessEntityID = p.BusinessEntityID
INNER JOIN
Anchor a ON a.OrganizationNode.IsDescendantOf(e.OrganizationNode) = 1外部SELECT将加入HumanResources.Employee和Person.Person表,并获取露丝·埃勒布鲁克( Ruth )的OrganizationNode列是另一行的后代的所有行--例如,它将列出露丝·埃勒布鲁克的所有直接上级,直到首席执行官。
https://stackoverflow.com/questions/21872195
复制相似问题