我需要创建一个查询,从表A中选择所有内容,此外还有一个列,指示A.col1
的值在B.col2
中的次数。
示例:
表A:
id name
1 "y"
2 "z"
3 "w"
表B:
id name
15 "y"
23 "w"
14 "y"
我想要一个能够提供以下内容的查询:
id name numOfTimes
1 "y" 2 // y is shown twice in table B
2 "z" 0 // z isn't shown in table B
3 "w" 1 // w is shown once in table B
答案 0 :(得分:2)
试试这个:
Select a.id, a.name, count(b.id) as numoftimes from a
left outer join b on a.name = b.name
group by a.id, a.name;
答案 1 :(得分:0)
可以通过多种方式完成
select a.id as Id
,a.name as Name
,(select count(1) from b where a.id=b.id) as NumberOfTimes
from a;
或
select a.id as Id
,a.name as Name
,count(b.id) as NumberOfTimes
from a
left join b on a.id=b.id;
答案 2 :(得分:0)
尝试以下操作即可获得预期结果。
选择a.id,a.col1,count(b.col1)为numOfTimes
来自TableA的左连接TableB b
on a.col1 = b.col1
分组由a.id,a.col1;
组成感谢。