求一条存储过程的写法
sql server 2005
表:table1
字段:a1,a2
字段a1的值是1到9之间的整数
字段a2的值是1或者null
表数据如下
a1,a2
1,1
2,1
9,1
1,1
存储过程如下:
CREATE PROCEDURE p1
AS
BEGIN
select a1, count(a2) as a2 from table1 group by a1
因为表中a1的数据只有1,2,9,所以得到结果
a1,a2
1,2
2,1
9,1
如果想得到结果
a1,a2
1,2
2,1
3,0
4,0
5,0
6,0
7,0
8,0
9,1
在不对表table1增加数据的前提下,应该怎么改这个存储过程。
谢谢
------解决方案--------------------CREATE PROCEDURE p1
AS
BEGIN
select
A.a1,
count(B.a2) as a2
from
(Select 1 As a1
Union All Select 2
Union All Select 3
Union All Select 4
Union All Select 5
Union All Select 6
Union All Select 7
Union All Select 8
Union All Select 9) A
Left Join
table1 B
On A.a1 = B.a1
group by A.a1
END
GO