CASE WHEN

时间:2015-09-18 09:55:48

标签: sql postgresql

我有一种情况,我使用案例多次使用相同的条件检查,查询如下

SELECT wcrus_status.emucarid,
   CASE
       WHEN (((wcrus_status.healthstatus = -1)
              AND (
                     (SELECT eventtime
                      FROM wcru_latestevents
                      WHERE wcrus_status.emucarid = wcru_latestevents.emucarid
                        AND wcru_latestevents.eventuei = 'uei.opennms.org/rfnet-WCRU/ntpSyncTrap') > wcrus_status.startuptime))
             OR ((wcrus_status.healthstatus <> -1)
                 AND (
                        (SELECT eventtime
                         FROM wcru_latestevents
                         WHERE wcrus_status.emucarid = wcru_latestevents.emucarid
                           AND wcru_latestevents.eventuei = 'uei.opennms.org/rfnet-WCRU/ntpSyncTrap') > wcrus_status.startuptime)
                 AND (
                        (SELECT eventtime
                         FROM wcru_latestevents
                         WHERE wcrus_status.emucarid = wcru_latestevents.emucarid
                           AND wcru_latestevents.eventuei = 'uei.opennms.org/rfnet-WCRU/ntpSyncTrap') > wcrus_status.posttime))) THEN ()
       ELSE wcrus_status.ntp
   END AS ntp
FROM wcrus_status

我尝试使用WITH来选择在CASE WHEN中使用的事件时间,但没有成功。有人可以指出我如何优化这个查询,而不是多次重复相同的子查询吗?

2 个答案:

答案 0 :(得分:1)

有些事情:

with data as (
  SELECT wcrus_status.emucarid,
         wcrus_status.healthstatus,
         wcrus_status.startuptime,
         wcrus_status.posttime,
         wcrus_status.ntp,
         (SELECT eventtime
          FROM wcru_latestevents
          WHERE wcrus_status.emucarid = wcru_latestevents.emucarid
            AND wcru_latestevents.eventuei = 'uei.opennms.org/rfnet-WCRU/ntpSyncTrap') as eventtime
  FROM wcrus_status
)
select emucarid,
       case 
         when (((healthstatus = -1 AND eventtime > startuptime) OR healthstatus <> -1 AND eventtime > wcrus_status.startuptime) AND ....
         ELSE ntp
       END AS ntp
from data;

答案 1 :(得分:0)

  

注意:此解决方案适用于 MSSQL

这个怎么样..

Declare @date as date

SELECT @date = eventtime
FROM wcru_latestevents
WHERE wcrus_status.emucarid = wcru_latestevents.emucarid
AND wcru_latestevents.eventuei = 'uei.opennms.org/rfnet-WCRU/ntpSyncTrap'

SELECT wcrus_status.emucarid,
   CASE
    WHEN (((wcrus_status.healthstatus = -1)
        AND (
                @date > wcrus_status.startuptime))
        OR ((wcrus_status.healthstatus <> -1)
            AND (
                @date > wcrus_status.startuptime)
            AND (
                @date > wcrus_status.posttime))) THEN ()
       ELSE wcrus_status.ntp
   END AS ntp
FROM wcrus_status