现在有表A和表B
index字段是表A中的主键
index字段也会在表B中出现,可能出现若干条
现在我想用一条Select语句,把表A中的记录查询出来,并获得表B中相同index的条数
请问如何查询?
------解决方案--------------------
同库的话dbo可去掉
SELECT A.index , B.index
FROM A, B
Where A.index = B.index
------解决方案--------------------
试试这个:
SELECT A.*, (select count(*) from B where A.index = B.index) as 'b表中的条数'
FROM A
------解决方案--------------------
select a.*,b.[条数]
from a inner join (select index,count(1) [条数] from b group by index) b on a.index=b.index
------解决方案--------------------
SELECT A.*, (select count(*) from B where A.index = B.index) as 'b表条数'
FROM A
------解决方案--------------------
SELECT A.*,C.条数 FROM A JOIN (SELECT *,ROW_NUMBER() OVER(PARTITION BY B.ID ORDER BY B.ID)AS 条数 FROM B)C
ON A.INDEX=C.INDEX
------解决方案--------------------
select a.*,
isnull(b.qty,0) 'qty'
from 表A a
left join (select [index],
count(1) 'qty'
from 表B
group by [index]) b on a.[index]=b.[index]
------解决方案--------------------
这个语句 精炼 学习了