Tsql 比较两个表中的行数
我有两个表,它们共享一列,这不是唯一的。我想要表A的共享列的值比表B的多的所有记录Tsql 比较两个表中的行数,tsql,join,Tsql,Join,我有两个表,它们共享一列,这不是唯一的。我想要表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 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
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
但这似乎产生了一个交叉连接,我得到的是joe | 6 | 6
,而不是3和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
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 |
对于
joe
,tablea\u count
=3如何?我不明白你是怎么计算的。希望这足够清楚。两个真正的表都是巨大的,所以我试图将信息缩减到基本的相同A。共享列值总是伴随着相同的A。用户ID
值?不,用户ID在B中不存在。B有其他数据。好的,但是我不是说B
。