使用WHERE过滤CASE语句

时间:2014-03-25 16:03:54

标签: sql postgresql

我想过滤CASE语句中列出的变量的结果集。

SELECT u.id,
max(t.request_at) AS "Date",
sum(CASE
    WHEN t.view = 1 THEN 1
    ELSE 0 END) AS ONE,
sum(CASE
    WHEN t.view = 2 THEN 1
    ELSE 0 END) AS TWO,
sum(CASE
    WHEN t.view = 3 THEN 1
    ELSE 0 END) AS THREE

FROM users u

JOIN t ON u.id = t.uid

WHERE u.signup_city_id = 18
AND u.creationtime BETWEEN '2013-12-01' AND '2014-01-01'

group by 1

我真的想过滤掉以下内容:WHERE ONE< 3

即。第一列小于3。

3 个答案:

答案 0 :(得分:1)

您需要将其包装到派生表中:

select *
from (
    SELECT u.id,
           max(t.request_at) AS "Date",
           sum(CASE
               WHEN t.view = 1 THEN 1
               ELSE 0 END) AS ONE,
           sum(CASE
               WHEN t.view = 2 THEN 1
               ELSE 0 END) AS TWO,
           sum(CASE
               WHEN t.view = 3 THEN 1
               ELSE 0 END) AS THREE
    FROM users u
      JOIN t ON u.id = t.uid
    WHERE u.signup_city_id = 18
      AND u.creationtime BETWEEN '2013-12-01' AND '2014-01-01'
    group by 1
) t
WHERE ONE < 3

答案 1 :(得分:1)

您将使用having子句:

SELECT u.id, max(t.request_at) AS "Date",
       sum(CASE WHEN t.view = 1 THEN 1 ELSE 0 END) AS ONE,
       sum(CASE WHEN t.view = 2 THEN 1 ELSE 0 END) AS TWO,
       sum(CASE WHEN t.view = 3 THEN 1 ELSE 0 END) AS THREE
FROM users u JOIN
     t
     ON u.id = t.uid
WHERE u.signup_city_id = 18 AND u.creationtime BETWEEN '2013-12-01' AND '2014-01-01'
group by 1
HAVING sum(CASE WHEN t.view = 1 THEN 1 ELSE 0 END) < 3;

或者使用子查询:

SELECT t.*
FROM (SELECT u.id, max(t.request_at) AS "Date",
             sum(CASE WHEN t.view = 1 THEN 1 ELSE 0 END) AS ONE,
             sum(CASE WHEN t.view = 2 THEN 1 ELSE 0 END) AS TWO,
             sum(CASE WHEN t.view = 3 THEN 1 ELSE 0 END) AS THREE
      FROM users u JOIN
           t
           ON u.id = t.uid
      WHERE u.signup_city_id = 18 AND u.creationtime BETWEEN '2013-12-01' AND '2014-01-01'
      group by 1
     ) t
WHERE ONE < 3;

答案 2 :(得分:0)

您可以在SUM子句中使用CASE语句的WHERE结果,如下所示:

SELECT u.id,
    max(t.request_at) AS "Date",
SUM(CASE
    WHEN t.view = 1 THEN 1
    ELSE 0 END) AS ONE,
SUM(CASE
    WHEN t.view = 2 THEN 1
    ELSE 0 END) AS TWO,
SUM(CASE
    WHEN t.view = 3 THEN 1
    ELSE 0 END) AS THREE
FROM users u
JOIN t ON u.id = t.uid
WHERE u.signup_city_id = 18
AND u.creationtime BETWEEN '2013-12-01' AND '2014-01-01'
GROUP BY 1
HAVING SUM(CASE
    WHEN t.view = 1 THEN 1
    ELSE 0 END) < 3