仅当> MSsql选择计数情况0

时间:2015-08-19 16:32:59

标签: sql sql-server

我有一个查询,选择并显示符合条件的所有值

WITH cte AS ( 
    SELECT row_number() OVER(order by cars.make ASC,cars.model ASC) AS rn, cars.id, cars.make 
        FROM cars 
        LEFT JOIN transport ON cars.transportfrom=transport.id 
        WHERE Make in ('DAIHATSU','DODGE','JEEP','KIA','LANCIA')
) 
SELECT make, count(CASE WHEN RN BETWEEN 51 AND 100 THEN 1 END) AS CountInResponse, count(1) AS total 
    FROM cte 
    GROUP BY make

我得到了结果

make        |   CountInResponse |   total
DAIHATSU    |   0               |   5
DODGE       |   0               |   2
JEEP        |   0               |   14
KIA         |   10              |   39
LANCIA      |   17              |   17

但是如何只得到>的结果0?

make        |   CountInResponse |   total
KIA         |   10              |   39
LANCIA      |   17              |   17

1 个答案:

答案 0 :(得分:2)

===

您应该在最后添加WITH cte AS ( SELECT row_number() OVER(order by cars.make ASC,cars.model ASC) AS rn, cars.id, cars.make FROM cars LEFT JOIN transport ON cars.transportfrom=transport.id WHERE Make in ('DAIHATSU','DODGE','JEEP','KIA','LANCIA') ) SELECT make, count(CASE WHEN RN BETWEEN 51 AND 100 THEN 1 END) AS CountInResponse, count(1) AS total FROM cte GROUP BY make having count(CASE WHEN RN BETWEEN 51 AND 100 THEN 1 END) > 0 子句。