从同一个表中选择两次信息

时间:2013-07-25 19:57:42

标签: sql tsql

我需要一个表来提取信息。

SELECT [workID], [name], [status], [nextStep] FROM [JM_AccountWorkFlowDetail]

[nextStep]指向链中的下一步(如果可用)将匹配workID中的内容。

以上查询将返回:

workID  name                        status  nextStep
7       Name                        Status     0
9       Garnishment to Court        WWW        7

正如您在workID 9中看到的那样,它指向7,这意味着workID 7是列表中的下一个。

是否可以显示nextStep的名称而不是数字?

将返回以下内容的查询:

workID  name                        status  nextStep
7       Name                        Status     0
9       Garnishment to Court        WWW        Name

3 个答案:

答案 0 :(得分:4)

将其与表格本身相关联,以便通过将其与nextStep相关联来获取workid的名称。

SELECT  a.workID,
        a.name,
        a.status,
        COALESCE(b.name, CAST(a.nextStep AS VARCHAR(5))) nextStepName
FROM    JM_AccountWorkFlowDetail a
        LEFT JOIN JM_AccountWorkFlowDetail b
            ON a.nextStep = b.workID  

答案 1 :(得分:1)

   ; with
    cte1 as
    (
        SELECT 

        JM.[workID]
        ,JM.[name]
        ,JM.[status]
        ,(select top 1 name from JM_AccountWorkFlowDetail where nextStep = JM.nextStep) nextStep
        FROM [JM_AccountWorkFlowDetail] JM
    )

    select workid, name, status, case when nextstep=0 then 'no next step' else nextstep end
    from cte1

答案 2 :(得分:0)

SELECT a.[workID], a.[name], a.[status], b.name as nextstep FROM [JM_AccountWorkFlowDetail] a
right outer join [JM_AccountWorkFlowDetail] b
on b.nextstep=a.nextstep