2015-10-17 58 views
0

他我想用多個嵌套案例查詢構建sql查詢。Sqlite嵌套案例查詢

我的表有這個列:ID,UserId,EventInTime,InTime,EventOutTime,OutTime。

這裏是列僞代碼,困擾我:

(If EventInTime ==0 then IT = InTime else IT = EventInTime; 
If EventOutTime ==0 then IT = OutTime else OT = EventOutTime; 
If IT or OT ==0 then 0 else OT-IT) as Suma 

繼承人我的代碼:

SELECT 
UserId, 
StatId, 
case when 
    case when EventInTime =0 
    then InTime 
    else EventInTime end=0 
    or 
     case when EventOutTime =0 
     then OutTime 
     else EventOutTime end 
     then 0 
else 
    case when EventOutTime =0 
    then OutTime 
    else EventOutTime end - 
     case when EventInTime =0 
     then InTime 
     else EventInTime end 
     as suma 
from Worktimes 

我在做什麼錯?

回答

1

靠在第二內殼的值的零比較丟失:

SELECT UserId, 
     StatId, 
     CASE 
     WHEN CASE EventInTime 
      WHEN 0 THEN InTime 
        ELSE EventInTime 
      END = 0 
      OR 
      CASE EventOutTime 
      WHEN 0 THEN OutTime 
        ELSE EventOutTime 
      END = 0     -- !!! 
     THEN 0 
     ELSE CASE EventOutTime 
      WHEN 0 THEN OutTime 
        ELSE EventOutTime 
      END 
      - 
      CASE EventInTime 
      WHEN 0 THEN InTime 
        ELSE EventInTime 
      END 
     END AS Suma 
FROM Worktimes; 

IT和OT是零僅當兩個列都是零,所以第2內的情況下可以簡化爲:

SELECT UserId, 
     StatId, 
     CASE 
     WHEN (InTime = 0 AND EventInTime = 0) OR 
      (OutTime = 0 AND EventOutTime = 0) 
     THEN 0 
     ELSE CASE EventOutTime 
      WHEN 0 THEN OutTime 
        ELSE EventOutTime 
      END 
      - 
      CASE EventInTime 
      WHEN 0 THEN InTime 
        ELSE EventInTime 
      END 
     END AS Suma 
FROM Worktimes; 

的另一種方式,使查詢簡單的將是引進ITOT虛擬列(這需要一個單獨的子查詢):

SELECT UserId, 
     StatId, 
     CASE WHEN IT = 0 OR OT = 0 
      THEN 0 
      ELSE OT - IT 
     END AS Suma 
FROM (SELECT UserId, 
      StatId, 
      CASE EventInTime 
        WHEN 0 THEN InTime 
        ELSE EventInTime 
      END AS IT, 
      CASE EventOutTime 
        WHEN 0 THEN OutTime 
        ELSE EventOutTime 
      END AS OT 
     FROM Worktimes);