根据存储过程的另一个表从一个表中选择值

时间:2016-09-08 21:33:28

标签: sql-server tsql stored-procedures

我有以下存储过程:

select 
    assn as Association, count(id) as Total
from 
    Farmers
where 
    assn is not null
group by 
    assn
order by 
    assn asc

生成此表:

enter image description here

任何人都可以帮助我使用第二个表中的关联列中的值填充上面的Association列:

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为你正在寻找这个

SELECT f.assn AS AssociationId,
       a.Association,
       COUNT(f.id) AS Total
FROM Farmers f
     INNER JOIN YourSecondTable a ON f.assn = a.id
WHERE assn IS NOT NULL
GROUP BY assn,
         a.Association
ORDER BY assn ASC;

将YourSecondTable替换为第二个表的名称