首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Union ALL读取空行

Union ALL读取空行
EN

Stack Overflow用户
提问于 2012-07-11 20:34:32
回答 3查看 2.7K关注 0票数 0

我有两个连接了union All的查询。

代码语言:javascript
复制
SELECT  select 'Finished' AS Status,amount AS amount,units As Date
from table1 WHERE Pdate > cdate AND name =@name
UNION ALL
SELECT  select 'Live' AS Live,amount,units 
from table1  Where Pdate = cdate And name =@name

结果

代码语言:javascript
复制
Status     amount   units
Finished     100    20
Live         200    10

当两个查询中的任何一个读取空集时,我只得到一行,如果两个查询都读取空集,则我没有行

那么我怎么才能得到这样的结果呢?

代码语言:javascript
复制
Status     amount   Units
Finished     100    20
Live         0      0

代码语言:javascript
复制
Status     amount   Units
Finished     0      0
Live         200    10

代码语言:javascript
复制
Status     amount   Units
Finished      0          0
Live          0          0

谢谢。

EN

回答 3

Stack Overflow用户

发布于 2012-07-11 20:39:41

我认为你可以使用sum来做这件事?如果在没有行的情况下sum不返回0,则替换为Coalesce(sum(amount), 0) as amount

代码语言:javascript
复制
SELECT  select 'Finished' AS Status,sum(amount) AS amount, sum(units) As Unit
from table1 WHERE Pdate > cdate AND name =@name
UNION ALL
SELECT  select 'Live' AS Status, sum(amount) as amount, sum(units) as Unit
from table1  Where Pdate = cdate And name =@name

如果你不想对结果求和,那么只需要合并就行了?coalesce(amount, 0) As amount等等。

票数 1
EN

Stack Overflow用户

发布于 2012-07-11 21:23:13

我只想指出,您的查询是不必要的复杂,具有嵌套的selects和union all。编写查询的更好方法是:

代码语言:javascript
复制
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

该查询不会产生您想要的结果,因为它只产生有数据的行。

获得额外行的一种方法是增加原始数据,然后检查是否需要它。

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-07-14 21:44:24

试试这样的东西

代码语言:javascript
复制
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 =@name 
UNION ALL 
select 'Live' ,amount,units  
from table1  Where Pdate = cdate And name =@name 
)
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11432776

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档