重写 SQL 脚本而不重复相同的嵌套查询

Rewrite SQL script without repeating same nested queries

我有 @a@b@c@d 声明的变量。

如何在不多次创建相同的嵌套查询的情况下重写以下代码?

SELECT @a, @b, COUNT(DISTINCT id)
FROM Table t
WHERE @a IN
        (SELECT col FROM Table
        WHERE id = t.id)
AND @b IN
        (SELECT col FROM Table
        WHERE id = t.id)
AND @c NOT IN
        (SELECT col FROM Table
        WHERE id = t.id)
AND @d NOT IN
        (SELECT col FROM Table
        WHERE id = t.id)

您可以使用条件聚合方法

SELECT @a, @b,COUNT(id)
FROM   (SELECT id
        FROM   [Table]
        GROUP  BY id
        HAVING MAX(CASE WHEN col = @a THEN 1 ELSE 0 END) = 1 AND 
               MAX(CASE WHEN col = @b THEN 1 ELSE 0 END) = 1 AND
               MAX(CASE WHEN col = @c THEN 1 ELSE 0 END) = 0 AND
               MAX(CASE WHEN col = @d THEN 1 ELSE 0 END) = 0
                ) T