将工作查询合并为一个查询,并在结果集中包含多列

时间:2019-01-02 15:00:43

标签: sql db2

我有2个基本查询,都可以按预期方式工作并返回预期结果:

select
  empNumber,
  sum(salesPrice) as categorySales
from testSchema.sales 
where empNumber = 12345
and date between '2018-01-01' and '2018-04-31'
and g.category = 'NewCategory'
group by empNumber;

select
  empNumber,
  sum(salesPrice) as totalSales
from testSchema.sales 
where empNumber = 12345
and date between '2018-01-01' and '2018-04-31'
group by empNumber;

但是,我想将它们组合成一个查询,该查询将每个结果作为自己的列返回。目前,这两个查询之间的主要区别是附加的AND子句创建了一个特定的值。目前的结果是

第一个查询:

empNumber  |  categorySales
----------------------------
12345               15603.00

第二个查询:

empNumber  |  totalSales
----------------------------
12345           350253.00

但是我想找到一种高性能且可扩展的方式来将它们结合起来

所需结果:

empNumber  |  categorySales  |  totalSales
-----------------------------------------------
12345           15603.00            350253.00

实现此目的最有效的方法是什么,以便将来我可以添加更多子句并返回一个结果集?

2 个答案:

答案 0 :(得分:1)

将两者结合起来(如果您没有重复的值)的最简单方法是FULL JOIN

尝试一下

with c as(
select
  empNumber,
  sum(salesPrice) as categorySales
from testSchema.sales 
where empNumber = 12345
and date between '2018-01-01' and '2018-04-31'
and g.category = 'NewCategory'
group by empNumber
), d as(
select
  empNumber,
  sum(salesPrice) as totalSales
from testSchema.sales 
where empNumber = 12345
and date between '2018-01-01' and '2018-04-31'
group by empNumber
)
Select isnull(c.empNumber,d.empNumber) as empNumber
      ,c.categorySales
      ,d.totalSales
  from c full join d ON (c.empNumber = d.empNumber)

答案 1 :(得分:-1)

where中包含通用条件并有条件地进行汇总,即使用case表达式。

select
  empNumber,
  sum(case when category = 'NewCategory' then salesPrice else 0 end) as categorySales,
  sum(salesPrice) as totalSales
from testSchema.sales 
where empNumber = 12345
and date between '2018-01-01' and '2018-04-30'
group by empNumber;