请帮助合并这两个查询,我尝试使用UNION
并获得结果错误
- 第一次查询
select p.pegawainama,r.pegawainid, sum(cast(round(r.besarpotongan,0) as int)) as totalpotnondinas
from
rpotongan r
inner join
pegawai p on p.pegawainid=r.pegawainid
where
r.nojenpot not in (1,7,6,12,14)
--and r.pegawainid = '6290134A'
and r.bulan = '3'
and r.tahun = '2012'
and p.kodebayar = '152012'
group by
r.pegawainid,
p.pegawainama
order by
p.pegawainama,
sum(cast(round(r.besarpotongan,0) as int))
- 第二次查询
select p.pegawainama, r.pegawainid, sum(cast(round(r.besarpotongan,0) as int)) as totalpotdinas from rpotongan r
inner join
pegawai p on p.pegawainid=r.pegawainid
where
r.nojenpot in (1,7,6,12,14)
--and r.pegawainid = '6290134A'
and r.bulan = '3'
and r.tahun = '2012'
and p.kodebayar = '152012'
group by
r.pegawainid,
p.pegawainama
order by
p.pegawainama,
sum(cast(round(r.besarpotongan,0) as int))
答案 0 :(得分:0)
要使用UNION
,您需要使用相同的列名,因此一个查询中不能totalpotnondinas
而另一个查询中不能totalpotdinas
。
您可以做的是调用两列totals
并添加一个额外的列,指示哪个查询是数据源。例如:
select p.pegawainama,r.pegawainid, sum(cast(round(r.besarpotongan,0) as int)) as total,
'potnondinas' as src from rpotongan r inner join pegawai p on p.pegawainid=r.pegawainid
where r.nojenpot not in (1,7,6,12,14) --and r.pegawainid = '6290134A' and r.bulan = '3'
and r.tahun = '2012' and p.kodebayar = '152012' group by r.pegawainid, p.pegawainama
order by p.pegawainama, sum(cast(round(r.besarpotongan,0) as int))
- 第二次查询
select p.pegawainama, r.pegawainid, sum(cast(round(r.besarpotongan,0) as int)) as total,
'potdinas' as src from rpotongan r inner join pegawai p on p.pegawainid=r.pegawainid
where r.nojenpot in (1,7,6,12,14) --and r.pegawainid = '6290134A' and r.bulan = '3'
and r.tahun = '2012' and p.kodebayar = '152012' group by r.pegawainid, p.pegawainama
order by p.pegawainama, sum(cast(round(r.besarpotongan,0) as int))
如果省略合成src
列,UNION
将合并相同的结果。
答案 1 :(得分:0)
不确定这两个不同的查询除了不同的别名之外是怎样的,但是ORDER BY
中只能有一个UNION
(错误消息应该已经告诉了你)。尝试:
select p.pegawainama,r.pegawainid, sum(cast(round(r.besarpotongan,0) as int))
as totalpotnondinas
from
rpotongan r
inner join
pegawai p on p.pegawainid=r.pegawainid
where
r.nojenpot not in (1,7,6,12,14)
--and r.pegawainid = '6290134A'
and r.bulan = '3'
and r.tahun = '2012'
and p.kodebayar = '152012'
group by
r.pegawainid,
p.pegawainama
union all
select p.pegawainama, r.pegawainid, sum(cast(round(r.besarpotongan,0) as int))
as totalpotnondinas
from
rpotongan r
inner join
pegawai p on p.pegawainid=r.pegawainid
where
r.nojenpot in (1,7,6,12,14)
--and r.pegawainid = '6290134A'
and r.bulan = '3'
and r.tahun = '2012'
and p.kodebayar = '152012'
group by
r.pegawainid,
p.pegawainama
order by
pegawainama,
totalpotnondinas;
如果您希望SUM()
列在两个结果之间可以辨认,请在第一个查询中使用SUM... AS col1, NULL AS col2
,在第二个查询中使用NULL AS col1, SUM... AS col2
。