仅为多个选择定义子选择查询一次

时间:2013-03-08 17:07:40

标签: sql sql-server

我正在写一个选择查询,我必须在两个地方编写相同的子查询

select e.MasterAccNumber from (
select MasterAccNumber from ACE_AccsLevelTran where CAST(timstmp as DATE) = '02/06/2013' 
union all
select m.AccountNumber from ACE_InvLevelTran i left join ACE_InvLevelMaster m i.MasterInvNumber=m.InvoiceNo 
where CAST(i.timstmp as date) ='02/06/2013' ) as e where e.MasterAccNumber not in( 
select e.MasterAccNumber from e group by e.MasterAccNumber having COUNT( e.MasterAccNumber) > 1 )

这里在最后一个子查询中,解析器无法理解对象e

select e.MasterAccNumber from e group by e.MasterAccNumber having COUNT( e.MasterAccNumber) > 1 

如何写这样我多次没有定义“e”。

1 个答案:

答案 0 :(得分:0)

select MasterAccNumber from 
(
select MasterAccNumber from ACE_AccsLevelTran where CAST(timstmp as DATE) = '02/06/2013' 
union all
select m.AccountNumber from ACE_InvLevelTran i 
left join ACE_InvLevelMaster m i.MasterInvNumber=m.InvoiceNo 
where CAST(i.timstmp as date) ='02/06/2013' 
)  e
group by MasterAccNumber 
having COUNT( MasterAccNumber) < 2