计算案例或如果为空

时间:2015-04-17 20:14:48

标签: mysql if-statement case

我很难弄清楚如何在这里整合我的逻辑。

有两种情况:

  1. cn.create_time为null
  2. cn.create_time不为null,在这种情况下它包含时间戳
  3. 我的选择查询的开头如下所示:

    select
        c.eid,
        count(c.eid),
        count(case when c.last_mod < cn.create_time then c.eid end)
    

    但我需要的是使case语句的行(在EnSQLish中)

    "if cn.create_time is null then count(c.last_mod), else count(case when c.last_mod < cn.create_time then c.eid end)."
    

    换句话说,如果create_time为null,则计算所有记录,否则只计算last_mod小于create_time的记录。

    我该怎么做?

3 个答案:

答案 0 :(得分:2)

你在找这样的东西吗?

SELECT  c.eid,
        COUNT(c.edi),
        SUM
        (
            CASE
                WHEN cn.create_time IS NULL OR c.last_mod < cn.create_time THEN 1
                ELSE 0
            END
        )

答案 1 :(得分:1)

我在指标上使用SUM()

选择     c.eid,     sum(IF(c.last_mod&lt; coalesce(cn.create_time,c.last_mod),0,1)),

如果cn.create_time为空,coalesce将返回c.last_mod

答案 2 :(得分:0)

您可以进行两次查询而不是一次:

select eid, count(eid) FROM Table WHERE create_time IS NULL
select eid, count(eid) FROM Table WHERE NOT create_time IS NULL AND last_mod < create_time

然后,如果你需要,你可以加入。