为什么我的union运算符查询只返回第一个选择的字段?

时间:2015-08-13 09:15:43

标签: sql

我需要从表格和值中获取所有值,条件为' not null'。 所以我发了两个SELECT语句。

select oa.dept_id, COUNT(oa.id) quantity, sum(oa.premium) 'sum'
from Table1 oa
    Left Join Table2 od On od.id = oa.dept_id
group by oa.dept_id

Union all

select oa1.dept_id, COUNT(oa1.id) quantity1, sum(oa1.premium) 'sum1'
from Table1 oa1
    Left Join Table2 od1 On od1.id = oa1.dept_id
where oa1.action is not null
group by oa1.dept_id

我希望 70行

这样的结果
-----------------------------------------------
| dept.id | quantity | sum | quantity1 | sum1 | 
-----------------------------------------------

我的结果是 130行

----------------------------
| dept.id | quantity | sum |
----------------------------

1 个答案:

答案 0 :(得分:2)

您需要使用加入

    select a.dept_id, quantity, sum,quantity1,sum1
    from 
    (
      select oa.dept_id, COUNT(oa.id) quantity, sum(oa.premium) 'sum'
      from Table1 oa
          Left Join Table2 od On od.id = oa.dept_id
      group by oa.dept_id
    ) a
    join
    (
      select oa1.dept_id, COUNT(oa1.id) quantity1, sum(oa1.premium) 'sum1'
      from Table1 oa1
          Left Join Table2 od1 On od1.id = oa1.dept_id
      where oa1.action is not null
      group by oa1.dept_id
    ) b
    on a.dept_id=b.dept_id