将2个查询组合成1个结果

时间:2015-11-23 09:18:48

标签: sql-server-2008

我有2个查询,如下所示:

SELECT brt.RequestTypeID, brt.RequestTypeName, brs.RequestStepName AS PreviousStep 
FROM b_Steps bs
INNER JOIN b_RequestStep brs ON bs.RequestStepID = brs.RequestStepID 
INNER JOIN b_RequestType brt ON bs.RequestTypeID = brt.RequestTypeID

第二个:

SELECT brt.RequestTypeID, brt.RequestTypeName, brs.RequestStepName AS NextStep 
FROM b_Steps bs 
INNER JOIN b_RequestStep brs ON bs.NextStepID = brs.RequestStepID 
INNER JOIN b_RequestType brt ON bs.RequestTypeID = brt.RequestTypeID

如何组合2个查询并返回如下结果:

| RequestTypeName | PreviousStep | NextStep      |
|------------------------------------------------|
| Buy good        | Login        | Add into cart |

2 个答案:

答案 0 :(得分:0)

试试这个

select a.RequestTypeName, a.PreviousStep, b.NextStep
from
(SELECT brt.RequestTypeID, brt.RequestTypeName, brs.RequestStepName AS PreviousStep 
FROM b_Steps bs 
INNER JOIN b_RequestStep brs ON bs.RequestStepID = brs.RequestStepID 
INNER JOIN b_RequestType brt ON bs.RequestTypeID = brt.RequestTypeID) as a
inner join 
(SELECT brt.RequestTypeID, brt.RequestTypeName, brs.RequestStepName AS NextStep 
FROM b_Steps bs 
INNER JOIN b_RequestStep brs ON bs.NextStepID = brs.RequestStepID 
INNER JOIN b_RequestType brt ON bs.RequestTypeID = brt.RequestTypeID) as b
on a.RequestTypeID = b.RequestTypeID

答案 1 :(得分:0)

接缝很容易,但也许我会想念:

SELECT brt.RequestTypeID, brt.RequestTypeName
,      brsp.RequestStepName AS PreviousStep 
,      brsn.RequestStepName AS NextStep 
FROM b_Steps bs
INNER JOIN b_RequestType brt ON bs.RequestTypeID = brt.RequestTypeID
LEFT JOIN b_RequestStep brsp ON bs.RequestStepID = brsp.RequestStepID 
LEFT JOIN b_RequestStep brsn ON bs.NextStepID = brsn.RequestStepID 

我不知道你是否有没有前一个或下一个的步骤,我在两种情况下都使用了左连接。