【问题标题】:SQL select if countSQL select if count
【发布时间】:2013-04-02 13:11:17
【问题描述】:

我有两张桌子 事件(ID、日期) 提醒(事件 ID、类型) event.id 上的内部连接 ​​=reminder.incidentID

并且我想仅在 event.id 有超过 4 个提醒时才使用它。ty​​pe = 15 我认为是

SELECT incident.id
FROM incident
INNER JOIN reminder ON incident.id = reminder.incidentid 
HAVING COUNT (reminder.remindertype = "something") >5
GROUP BY incident.incidentcode

我得到的错误是

第 6 行:'=' 附近的语法不正确。

我能做什么?

【问题讨论】:

    标签: sql sql-server database count


    【解决方案1】:

    COUNT 不能这样工作。

    试试:

    select incident.id
    from incident
    inner join reminder
    on incident.id = reminder.incidentid
    WHERE reminder.remindertype = "something"
    group by incident.incidentcode 
    having count (reminder.remindertype) >5
    

    【讨论】:

    • +1 但我相信在 HAVING 之前拥有 GROUP BY 是一种很好的做法(甚至大多数 DBMS 都要求这样做)
    【解决方案2】:

    group by 子句应在having 子句之前声明

    select incident.id
    from incident
    inner join reminder
    on incident.id = reminder.incidentid
    group by incident.incidentcode 
    having count (reminder.remindertype) >5
    

    【讨论】:

      【解决方案3】:

      你很接近:

      select incident.id
      from incident inner join
           reminder
           on incident.id = reminder.incidentid
      group by incident.incidentcode 
      having sum(case when reminder.remindertype = "something" then 1 else 0 end) >5
      

      您的原始语法不适用于大多数 SQL 方言。您需要条件聚合。

      【讨论】:

        猜你喜欢
        • 2016-05-21
        • 1970-01-01
        • 2012-04-29
        • 2014-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-10
        相关资源
        最近更新 更多