我有两个共享列的表,这不是唯一的。我想要所有记录,其中表A具有比表B更多的共享列值。
TABLE A:
Shared_Column|User_ID|Department
123 | joe| sales
123 | joe| sales
123 | joe| sales
124 | sam| ops
124 | sam| ops
TABLE B
Shared_Column|Other_Column
123 | 1
123 | 1
124 | 4
124 | 4
根据这些数据,我想要joe|sales
,而不是sam|ops
。我也可以将其作为输出:
USER|TABLE_A_COUNT|TABLE_B_COUNT
joe| 3| 2
sam| 2| 2
编辑:我尝试过像这样的联接:
select a.user_ID, count(a.shared_column) as 'TABLE_A_COUNT', count(b.shared_column) as 'TABLE_B_COUNT'
from a inner join b on a.shared_column = b.shared_column
group by a.user_ID
但是这似乎产生了交叉连接,我得到joe|6|6
而不是3和2
谢谢!
答案 0 :(得分:1)
看起来你想要这样的东西:
select a.user_id,
count(a.shared_column) TableA,
TableB
from tablea a
inner join
(
select count(*) TableB, Shared_column
from tableb
group by shared_column
) b
on a.Shared_Column = b.Shared_Column
group by a.user_id, TableB
结果:
| USER_ID | TABLEA | TABLEB |
-----------------------------
| joe | 3 | 2 |
| sam | 2 | 2 |