我有2种相同类型的表:T1和T2,具有4列(日期,标志,状态,计数)。我想计算表中计数的差异。我正在使用以下查询
`Select
T1.date,
T1.flag,
T1.status,
T1.counts,
T2.counts
(T1.count-T2counts)as difference
From T1
Left join T2
On T1.date=T2.date
And T1.flag=T2.flag
And T1.status=T2.status
`
答案 0 :(得分:0)
您可以使用union all
和group by
总结每个表中的内容:
select Date, flag, status, sum(count1) as count1, sum(count2) as count2,
( sum(count1) - sum(count2) ) as diff
from ((select Date, flag, status, counts as count1, 0 as count2 from table1) union all
(select Date, flag, status, 0, counts as count2 from table1)
) tt
group by Date, flag, status;
答案 1 :(得分:0)
您的查询中有几次错字。我对其进行了修改并添加了WITH语句,以便可以使用示例数据。结果看起来不错。
with T1 (mydate, flag, status, counts) as (select trunc(sysdate), 'Cat1', 1, '100'
from dual),
T2 (mydate, flag, status, counts) as (select trunc(sysdate), 'Cat1', 1, '50'
from dual)
Select
T1.mydate,
T1.flag,
T1.status,
T1.counts T1Count,
T2.counts T2Count,
(T1.counts-T2.counts)as difference
From T1
left join T2
On T1.mydate=T2.mydate
And T1.flag=T2.flag
And T1.status=T2.status