2015-10-15 33 views
-2

我試圖創建一個SQL查詢,但有一些真正的困難,並且不確定寫入它的最佳方式。我目前有2列,一列包含時間戳,另一列包含隨機信息。我希望時間戳按降序排列(很簡單),但對於輔助列,我想按以下順序輸出結果:SQL查詢以按日期降序和多個「like」子句得到結果

注意:這些%是故意的,因爲它們在REMAINING列中。

  1. '%[EVENT = agentStateEvent]%' - 第一
  2. %[EVENT = TerminalConnectionCreated]%」 - 第二
  3. 還有什麼過第三,第四等爲時間戳。

例如:

兩個柱子均是字符串(VARCHAR最大)

 

    TIMESTAMP  | REMAINING 
    TIMESTAMP 10:30 | %[EVENT=agentStateEvent][Agentid=424][Queue=45235]% 
    TIMESTAMP 10:30 | %[EVENT=TerminalConnectionCreated][Agentid=424][Queue=45235]% 
    TIMESTAMP:10.31 | %[EVENT=agentStateEvent][Agentid=425][Queue=453635]% 
    TIMESTAMP 10.31 | %[EVENT=TerminalConnectionCreated][Agentid=425][Queue=45235]% 
    TIMESTAMP 10.31 | %[EVENT=CallDropped][Agentid=425][Queue=45235]% 
    TIMESTAMP 10.32 | %[EVENT=TerminalConnectionCreated][Agentid=426][Queue=44235]% 
    TIMESTAMP 10.32 | %[EVENT=CallDropped][Agentid=426][Queue=45235]% 

這將需要被包在一個「喜歡」命令作爲列REMAINING包含很多更多的信息。

查詢我至今是:

select * from TimestampsStorage 
order by timestamp desc, remaining desc 
+0

請發佈'timestamp'和'remaining'列的完整內容示例。目前還不清楚它們的格式是什麼,儘管我想我明白你正在使用'%...%'來暗示這些是在「剩餘」中的子字符串。 –

+0

嗨,兩列都是字符串(varchar max)。 %.....%不是子字符串,它們實際上是字符串的一部分,即REMAINING列中的實際條目是%[hithere]%。如果我想要搜索,那麼select * from timestampsStorage where remaining ='%[hithere]%'如果這樣做有道理的話? –

+1

但是你說「_它需要用'like'命令包裝,因爲REMAINING列包含更多信息。」其他信息是什麼?請修改以上內容至少發佈一個完整示例。 –

回答

1

使用您正在尋找CASE ... WHEN

order by 
    timestamp, 
    case when remaining like '%[EVENT=agentStateEvent]%' then 1 
     when remaining like '%[EVENT=TerminalConnectionCreated]%' then 2 
     else 3 
    end; 

如果'%[EVENT=...'來總是先在remaining,你可以看看 '%' explicitley。這可能會加快查詢速度。

order by 
    timestamp, 
    case when remaining like '#%[EVENT=agentStateEvent]%' escape '#' then 1 
     when remaining like '#%[EVENT=TerminalConnectionCreated]%' escape '#' then 2 
     else 3 
    end; 
+0

這是完美的。非常感謝 :) –

0

可以在ORDER使用CASE表達式BY子句

select ... 
ORDER BY 
     [TIMESTAMP] 
    , CASE WHEN [REMAINING] = '%[EVENT=agentStateEvent]%' then 1 
      WHEN [REMAINING] = '%[EVENT=TerminalConnectionCreated]%' THEN 2 
      ELSE 3 
     END 
    , [REMAINING] 

NB:因爲我不知道你正在使用的數據庫管理系統;在[]在T-SQL