2012-07-11 72 views
0

我有两个查询加入union All联盟ALL取空行

SELECT select 'Finished' AS Status,amount AS amount,units As Date 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
SELECT select 'Live' AS Live,amount,units 
from table1 Where Pdate = cdate And name [email protected] 

结果

Status  amount units 
Finished  100 20 
Live   200 10 

当任一查询取空集,我只得到一个行,如果两者取空集,然后我没有行

所以,我怎样才能得到像这

Status  amount Units 
Finished  100 20 
Live   0  0 

OR

Status  amount Units 
Finished  0  0 
Live   200 10 

OR

Status  amount Units 
Finished  0   0 
Live   0   0 

感谢。

+2

您选择单位的日期和“活”的活。这不应该是单位作为单位和“现场”状态? – Dan 2012-07-11 12:41:40

回答

1

我会认为你可以使用总和?如果总和不返回0时没有行然后用Coalesce(sum(amount), 0) as amount

SELECT select 'Finished' AS Status,sum(amount) AS amount, sum(units) As Unit 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
SELECT select 'Live' AS Status, sum(amount) as amount, sum(units) as Unit 
from table1 Where Pdate = cdate And name [email protected] 

更换,如果你是不是想总结的结果那么就应该合并工作? coalesce(amount, 0) As amount等...

+0

您可能需要在“SELECT”语句中使用“GROUP BY”。 – 2012-07-11 12:43:38

+0

我不这么认为......我假设他想总结所有的记录。 – Dan 2012-07-11 12:46:31

+0

+1,OP希望显示两行,而不管每个分支中合格记录的数量(0..n)。但我认为OP希望空值显示为零。 – 2012-07-11 13:10:44

0

我只想指出,你的查询是不必要的复杂,嵌套选择和联合所有。编写查询的更好方法是:

select (case when pdate > cdate then 'Finished' else 'Live' end) AS Status, 
     amount AS amount, units As Date 
from table1 
WHERE Pdate >= cdate AND name = @name 

此查询不会生成您想要的内容,因为它只生成有数据的行。

获取附加行的一种方法是增加原始数据,然后检查是否需要。

select status, amount, units as Date 
from (select Status, amount, units, 
      row_number() over (partition by status order by amount desc, units desc) as seqnum 
     from (select (case when pdate > cdate then 'Finished' else 'Live' end) AS Status, 
        amount, units, name 
      from table1 
      WHERE Pdate >= cdate AND name = @name 
      ) union all 
      (select 'Finished', 0, 0, @name 
      ) union all 
      (select 'Live', 0, 0, @name 
      ) 
     ) t 
where (amount > 0 or units > 0) or 
     (seqnum = 1) 

这增加了你想要的额外行。然后列举它们,所以它们会以任何顺序走到最后。它们被忽略,除非它们是序列中的第一个。

0

尝试这样的事情

with stscte as 
(
select 'Finished' as status 
union all 
select 'Live' 
), 
datacte 
as(
select 'Finished' AS Status,amount AS amount,units As Date 
from table1 WHERE Pdate > cdate AND name [email protected] 
UNION ALL 
select 'Live' ,amount,units 
from table1 Where Pdate = cdate And name [email protected] 
) 
select sc.status,isnull(dc.amount,0) as amount,isnull(dc.unit,0) as unit 
from stscte sc left join datacte dc 
on sc.status = dc.status