外部应用将2行组合成1行和2列

时间:2016-06-08 19:52:15

标签: sql common-table-expression outer-apply

我正在尝试编写一个将多个外部应用连接结果组合成单行数据的查询。我玩过一些CTE,但我无法解决问题。

我想将多个连接结果显示为1行,第2列显示第2个连接结果

SELECT 
     E.[EventId]
    ,S_ID.[EventType]
    ,null as [RootCause2]

 FROM [AOE_Workflow].[dbo].[Event] E

    outer apply
    (
    select * from [AOE_Workflow].[dbo].[EventTypes] S
    WHERE E.EventID=S.EventID
    ) S

    outer apply
    (
    select * from [AOE_Workflow].[dbo].[EventType] S_ID
    WHERE S_ID.[EventTypeId]=S.[EventTypeId]
    ) S_ID

ORDER BY eventID desc

enter image description here

2 个答案:

答案 0 :(得分:1)

如果我没有弄错,可以使用简单的outer apply更轻松地指定LEFT JOIN

并排输出可以使用PIVOT完成。对于给定的查询,没有隐式排序顺序。这意味着,它将是随机的,这是第一个,即第二个(和第三个/第四个)。在我的SQL中,当您将(SELECT NULL)更改为适当的时候,您可以轻松控制排序。

SELECT p.*
FROM
(
    SELECT 
         E.[EventId]
        ,S_ID.[EventType]
        ,'EventType_' + CAST(ROW_NUMBER() OVER(PARTITION BY E.[EventId] ORDER BY(SELECT NULL)) AS VARCHAR(1)) AS ColumnName
    FROM [AOE_Workflow].[dbo].[Event] E
    LEFT JOIN [AOE_Workflow].[dbo].[EventTypes] S ON E.EventID=S.EventID
    LEFT JOIN [AOE_Workflow].[dbo].[EventType] S_ID ON S_ID.[EventTypeId]=S.[EventTypeId]
) AS tbl
PIVOT
(
    MIN(EventType) FOR ColumName IN(EventType_1,EventType_2,EventType_3,EventType_4)
) AS p

答案 1 :(得分:0)

您是否仍处于设计阶段,或者您是否受现有数据结构的限制?

每个事件类型似乎都是它自己的实体,因为根本原因,即 EventType ='没有权力'可能已经过期电池'或者“交流发电机坏”'作为根本原因, 所以你会加入事件的根本原因而不是事件类型。

CREATE TABLE Event
( eventId int NOT NULL,
  eventTypeId int not null,
  rootCauseId int not null,
  CONSTRAINT e_pk PRIMARY KEY (eventId)
);

CREATE TABLE EventType
( eventTypeId int NOT NULL,
  eventTypeDescription int not null,
  CONSTRAINT et_pk PRIMARY KEY (eventTypeId)
);

CREATE TABLE EventRootCause
( rootCauseId int NOT NULL,
  rootCauseDescription int not null,
  CONSTRAINT rc_pk PRIMARY KEY (rootCauseId)
);

select
     e.eventId
    ,et.EventTypeDescription as EventType
    ,rc.rootCauseDescription as RootCause2
from
    Event e 
left join
    EventType et
        on
            e.eventTypeId = et.EventTypeId
left join
    RootCause rc
        on
            e.rootCauseId = rc.RootCauseId
order by e.eventId