T-SQL查询显示所有过去的步骤,活动和将来的步骤

时间:2018-01-26 17:37:51

标签: sql-server tsql

我在SQL Server中有3个表:

map_table :(工作流程图路径)

stepId step_name 
----------------    
1      A
2      B
3      C
4      D
5      E

history_table

stepId  timestamp author
----------------------------
1       9:00am    John
2       9:20am    Mary

current_stageTable

 Id      currentStageId   waitingFor
 ------------------------------------        
 12345   3                Kat

我想编写一个查询来显示具有工作流状态的地图。喜欢这个结果:

step   name  time     author
----------------------------    
 1      A    9:00am    John
 2      B    9:20am    Mary
 3      C    waiting   Kat
 4      D    
 5      E

我试过左连接

select 
    m.stepId, m.step_name, h.timestamp, h.author
from  
    map_table m
left join  
    history_table h on m.stepId = h.stepId

我认为它会列出地图表中的所有记录,因为我使用的是左连接,但不知怎的,它只显示了3条来自历史表的记录。

所以我改为

select 
    m.stepId, m.step_name, h.timestamp, h.author
from 
    map_table m
left join 
    history_table h on m.stepId = h.stepId

union

select 
    m.stepId, m.step_name, '' as timestamp, '' as author
from 
    map_table m
where 
    m.stageId not in (select stageId from history_table)
order by 
    m.stepId

然后它几乎按照我的预期列出结果,但是如何添加第3个表来显示当前的活动阶段?

非常感谢你的帮助!!非常感谢。

2 个答案:

答案 0 :(得分:1)

看起来就像你问的那样:

with map_table as (
    select * from (values (1,'A')
    ,(2,'B')
    ,(3,'C')
    ,(4,'D')
    ,(5,'E')) t(stepId, step_name)
)
, history_table as (
    select * from (values 
    (1,'9:00am','John')
    ,(2,'9:20am','Mary')) t(stepId, timestamp, author)
)
, current_stapeTable as (
    select * from (values (2345, 3, 'Kat')) t(Id, currentStageId, waitingFor)
)

select
    m.stepId, m.step_name
    , time = coalesce(h.timestamp, case when c.waitingFor is not null then 'waiting' end)
    , author = coalesce(h.author, c.waitingFor)
from
    map_table m
    left join history_table h on m.stepId = h.stepId
    left join current_stapeTable c on m.stepId = c.currentStageId

答案 1 :(得分:0)

我认为联合符合数据并避免在多个联接上合并值。

with timeline as (
    select stepId, "timestamp" as ts, author from history_table
    union all
    select currentStageId, 'waiting', waitingFor from current_stageTable
)
select step_id, step_name, "timestamp", author
from
    map_table as m left outer join timeline as t
        on t.stepId = m.stepId