2011-12-28 24 views
0

这是我正在尝试做的概念。联合使用两个子句

我基本上有两套数据,一套用于当前信息,一套用于存档信息。我需要结合他们将它们全部显示在一个列表中。

我的查询比这个复杂得多,但为了简单起见,我刚刚发布了我需要做的一般想法。

我将如何得到这个为我工作?任何帮助是极大的赞赏。

(
    with m1 as 
    (
     select --distinct 
     pfa.FacilityID 
     from PatientFormCompleted 
    ) 
    select * from m1 
    left join other tables 
) 
union all 
(
    with m1archive as 
    (
     select --distinct 
     pfa.FacilityID 
     from PatientFormArchive 
    ) 
    select * from m1archive 
    left join other tables 
) 

回答

2

可能的,这将被关闭(投,没有downvoted,我BTW),但你的编辑之后,你也把一些精力的问题,所以这里去

您可以使用多个CTE的,但与

  • 他们彼此相随
  • 只有第一WITH被写入
约束

请注意,您不应该使用SELECT *,而应具体列出您想要返回的列。

SQL语句

with m1 as 
(
    select --distinct 
    pfa.FacilityID 
    from PatientFormCompleted 
) 
, m1archive as 
(
    select --distinct 
    pfa.FacilityID 
    from PatientFormArchive 
) 
select * from m1 
left join other tables 
union all 
select * from m1archive 
left join other tables 
+0

非常感谢你的帮助。这正是我需要的。 – 2011-12-28 18:43:20

+0

我现在有一个后续问题。如果我想把所有记录的总数作为一个总数来计算,那么我将如何去做这件事? – 2011-12-28 19:35:52

+1

没关系。得到它了。只需要一个别名。再次感谢你的帮助。 – 2011-12-28 19:41:27

1

两个选择:

联合成一个单一的CTE:

with m1 as 
(
    select --distinct 
    pfa.FacilityID 
    from PatientFormCompleted 

    union all 

    select --distinct 
    pfa.FacilityID 
    from PatientFormArchive 

) 
select * from m1 
left join other tables 

使用一个以上的CTE:

with m1 as 
(
    select --distinct 
    pfa.FacilityID 
    from PatientFormCompleted 
) 
,m1archive as 
(
    select --distinct 
    pfa.FacilityID 
    from PatientFormArchive 
) 
select * from m1 
left join other tables 
union all 
select * from m1archive 
left join other tables 
+0

+1在CTE中应用工会。 – 2011-12-28 18:46:36