SQL服务器查询UNION ALL

时间:2016-03-17 18:10:11

标签: sql sql-server union union-all

我有一个UNION ALL查询,我得到的结果不正确。我应该得到大约1100条记录。请参阅查询...

select 
    Pop, planID, PopFull, ApptDate, intake1,FollowUP2,FollowupCode, rn, '5133'
from 
    (Select *, row_number() over (partition by planID order BY AddedDate asc) as rn from Vinfo) t
where 
    rn = 1 and ApptDate >='12/1/2014' and ApptDate <='12/31/2015'

Union All

select  
    Pop, planID, PopFull, ApptDate, intake1, FollowUP2, FollowupCode, rn, '5133' 
from 
    (Select *,row_number() over (partition by PlanID order BY AddedDate  DESC) as rn from Vinfo) t
where 
    rn = 1 and ApptDate >='12/1/2014' and ApptDate <='12/31/2015'

所以我要做的是SELECT所有信息,在第一个SELECT语句中,当ADDEDDATE是最低(最早)时,我试图获得INTAKE的值。

我正在做 UNION all ,因为在第二个SELECT语句中,当ADDEDDATE是最旧的(最近的)时,我试图获取FOLLOWup的值。

INTAKE和FOLLOWUP的值可能不同,但并非必须如此。我正试图追踪差异。

然而,当我运行此查询时,我获得了两倍的记录。有没有办法让我运行这个查询,以便我可以获得正确的记录数(1100)并获得INTAKE的值,如果FOLLOWUP的值有变化,我会在同一行看到它?

而不是看到一切的双重。基本上它现在运行的方式是如果PLANID是1023并且EARLIEST日期的摄入量是B,那么它也将显示B用于FollowUP。另外如果,对于最新日期的跟进是C,那么它将在下面的行中显示C for Intake和FollowUP。

编辑:

select Pop,planID,PopFull,ApptDate, intake1,FollowUP2,FollowupCode, '5133'
from (select *,
row_number() over (partition by planID order BY AddedDate asc) as rn_first,
row_number() over (partition by PlanID order BY AddedDate  DESC) as rn_last
from VInfo
) t
where t.rn_first = 1 or rn_last = 1
and ApptDate >='12/1/2014' and ApptDate <='12/31/2015'

跑吧但没有给出正确的结果

1 个答案:

答案 0 :(得分:1)

对于那些只有一个Pop, planID, PopFull, ApptDate, intake1, FollowUP2, FollowupCode组合实例的行,显然会得到重复项 - 即ASC和DESC都返回一行,rn = 1,用于ASC和DESC排序。

UNION ALL确实允许来自顶部和底部行集的重复项。 您可以尝试使用UNION

另外,如前所述,您可以在单个选择中计算两个ROW_NUMBERS:

select *
from
(
  select v.*,
    row_number() over (partition by PlanID order BY AddedDate asc) as rn_first,
    row_number() over (partition by PlanID order BY AddedDate  DESC) as rn_last
  from Vinfo v
) t
where t.rn_first = 1 or rn_last = 1