2014-10-06 63 views
-2

我是SQL世界的新手,有人可以幫我解決這個問題。不匹配列中的數據

我有兩個表具有相同的列,CID,金額。兩者在數據插入方式上都有不同的邏輯,但技術上這兩個表的計數應該具有相同數量的CID。

在我的情況下,我確實有相同的計數給定期間,但我相信金額是不匹配的。

我想確定哪些CID存在錯誤金額並將此問題升級到級別4以查看業務邏輯。

有人可以告訴我如何找到不匹配的?

當我做:

select count(CID) from Table A 
union all 
select count(CID) from table B 

我得到1000兩個選擇。

+0

當然,我們可以嘗試去猜測你想要什麼,而是你怎麼樣提供至少有一個示例輸入與期望的輸出? – Alexander 2014-10-06 15:58:13

回答

0

這是很基本的,請通過一些教程後,現在 試試這個

如果你確信你有那麼兩個表中相同數量的記錄下面簡單的SQL會工作。 如果你在兩個表中都有不同的CID,那麼你需要使用Left和Right外部聯接來找出它們。

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 
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)