如何使用Count来表示具体情况

时间:2017-09-12 11:12:54

标签: sql-server-2012 ssms

我如何计算并显示有多少机会有阶段3但没有阶段2?

+-------+-------+
| OppID | Stage |
+-------+-------+
| ABC   |     1 |
| ABC   |     2 |
| ABC   |     3 |
| ABC   |     4 |
| CDF   |     3 |
| CDF   |     4 |
| EFG   |     1 |
| EFG   |     2 |
| EFG   |     3 |
| HIJ   |     2 |
| HIJ   |     3 |
| LMI   |     1 |
| LMI   |     2 |
| LMI   |     4 |
+-------+-------+

计数结果为1

+-------+-------+
| OppID | Stage |
+-------+-------+
| CDF   |     3 |
| CDF   |     4 |
+-------+-------+

1 个答案:

答案 0 :(得分:1)

知道了,你可以在下面使用NOT EXISTSCOUNT DISTINCT

SELECT COUNT(DISTINCT OppID) 
FROM tbl AS t1
WHERE NOT EXISTS (SELECT 1 FROM tbl AS t2 WHERE t1.OppID = t2.OppID and t2.Stage = 2) and t1.Stage = 3