group by子句的where子句也应该在sqlserver中返回count

时间:2014-01-25 04:28:50

标签: sql-server-2005

SELECT * FROM A
1 A  ACCEPT
2 A ACCEPT
3 C ACCEPT
4 C ACCEPT
5 B HOLD
6 G HOLD
7 G HOLD
8 B REJECT
9 G REJECT
10 H REJECT
11 H REJECT
12 A NEW
13 H REJECT
14 H NEW
15 C NEW
16 D NEW
17 E NEW
18 D ACCEPT
19 D ACCEPT
20 F ACCEPT
21 I NULL

这是我的桌子。

SELECT DISTINCT(PROD) FROM A
A
B
C
D
E
F
G
H
I

这些是我的产品。

SELECT PROD,ISNULL(COUNT(*),0) FROM A WHERE STATUS='ACCEPT' GROUP BY PROD
A 2
C 2
D 2
F 1

当我执行此操作时,我得到了上述结果

但我的要求是:

A   2
B   0
C   2
D   2
E   0
F   0
G   0
H   0
I    1

如何实现它。

请帮帮我

提前致谢

1 个答案:

答案 0 :(得分:0)

这应该是完美的:

SELECT T.PROD,SUM(T.FLAG) AS [COUNT]
FROM
(
SELECT PROD, 1 AS FLAG
FROM A
WHERE STATUS='ACCEPT'
UNION ALL 
SELECT PROD, 0 AS FLAG
FROM A
WHERE STATUS <>'ACCEPT'
) AS T
GROUP BY T.PROD
ORDER BY T.PROD