COUNT()超过结果

时间:2013-02-08 15:28:38

标签: sql tsql aggregation

我有一个类似的查询:

SELECT
    id
FROM
    table1
INNER JOIN
    ...
WHERE
    ...
    AND eventtype IN (2000120, 2000121, 2000122, 2000123, 2000130)

EXCEPT

SELECT
    id
FROM
    table1
INNER JOIN
    ...
WHERE
    ...
    AND eventtype IN (2000123,2000130,2000134,2000135)

请注意,除最后一个where子句外,查询都是相同的。

我现在想要计算上述查询返回的记录数。

如何?

非常感谢

3 个答案:

答案 0 :(得分:4)

使用COUNT并将其包装在SUBQUERY

SELECT COUNT(ID)
FROM (
        SELECT id
        FROM table1
        INNER JOIN...
        WHERE...
                AND eventtype IN ( 2000120, 2000121, 2000122, 2000123, 2000130 )
        EXCEPT
        SELECT id
        FROM table1
        INNER JOIN...
        WHERE...
                AND eventtype IN ( 2000123, 2000130, 2000134, 2000135 )
        ) s

答案 1 :(得分:1)

你只需要第一个查询你想要的东西,你不需要包含2000130值,如果你不需要它,那么你不想在查询中显示其他值。 / p>

SELECT
    id
FROM
    table1
INNER JOIN
    ...
WHERE
    ...
    AND eventtype IN (2000120, 2000121, 2000122, 2000123)

如果您需要从某个查询中排除某些值,可以使用

    AND eventtype NOT IN (2000130)

但不是两个一次。并根据需要计算常规使用SELECT COUNT(id)或子查询。

答案 2 :(得分:0)

您也可以将EXISTS与INTERSECT子查询一起使用

SELECT COUNT(ID)
FROM table1 t1 INNER JOIN ...
WHERE ... AND eventtype IN (2000120, 2000121, 2000122, 2000123, 2000130)
AND NOT EXISTS (
SELECT 1
FROM table1 t2 INNER JOIN ...
WHERE ... AND eventtype IN (2000123, 2000130, 2000134, 2000135)
AND EXISTS (SELECT t1.ID 
            INTERSECT
            SELECT t2.ID))