我是SQL世界的新手,有人可以帮我解决这个问题。
我有两个具有相同列的表,CID,Amount。两者都有关于如何插入数据的不同逻辑,但从技术上讲,两个表在计数中应具有相同数量的CID。
在我的情况下,我确实在给定的时间段内有相同的计数,但我相信金额是不匹配的。
我想确定哪个CID有错误金额,并将此问题上报到第4级以查看业务逻辑。
有人可以告诉我如何找到不匹配的内容吗?
当我这样做时:
select count(CID) from Table A
union all
select count(CID) from table B
我同时选择了1000。
答案 0 :(得分:1)
一个快速的小例子......
create table tempA (CID int);
create table tempB (CID int);
insert into tempA values (1);
insert into tempA values (2);
insert into tempA values (2);
insert into tempB values (1);
insert into tempB values (2);
insert into tempB values (3);
mysql> select * from tempA;
+------+
| CID |
+------+
| 1 |
| 2 |
| 2 |
+------+
mysql> select * from tempB;
+------+
| CID |
+------+
| 1 |
| 2 |
| 3 |
+------+
select case when tempA_ct.CID is not null then tempA_ct.CID
else tempB_ct.CID end as CID,
case when a_CID_ct is null then 0 else a_CID_ct end as CID_A_count,
case when b_CID_ct is null then 0 else b_CID_ct end as CID_B_count
from (select CID, count(CID) as a_CID_ct
from tempA
group by CID) as tempA_ct
full outer join (
select CID, count(CID) as b_CID_ct
from tempB
group by CID) as tempB_ct
on tempB_ct.CID=tempA_ct.CID
CID CID_A_COUNT CID_B_COUNT
1 1 1
2 2 1
3 0 1
4 1 0
这也可以写成:
select CID,
sum(case when tbln='A' then 1 else 0 end) as a_count,
sum(case when tbln='B' then 1 else 0 end) as b_count
from (select CID, 'A' as tbln
from tempA
union all
select CID, 'B' as tbln
from tempB) as joined
group by CID
+------+---------+---------+
| CID | a_count | b_count |
+------+---------+---------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 0 | 1 |
| 4 | 1 | 0 |
+------+---------+---------+
4 rows in set (0.04 sec)
答案 1 :(得分:0)
这是非常基础的,请稍后再阅读一些教程 试试这个
如果您确定两个表中的记录数相同,则可以使用以下简单的sql。 如果两个表中都有不同的CID,则需要使用左外连接和右外连接来查找它们。
select a.CID, a.amount 'TableA_amt', b.amount 'TableB_amt'
from TableA A inner join TableB B
ON a.CID=b.CID
Where a.amount <> b.amount