2013-02-28 124 views
1

我正在嘗試使用status列和DateSent列查詢表。在我的查詢中,我想將這兩列合併爲一個sent列 - 因此如果狀態爲c(已關閉/已發送),則顯示DateSent - 但如果不是,則顯示相應的狀態。如果日期爲空(SQL Server CE)

任何不是sent的行都將有DateSent作爲NULL。

下面

所需的輸出:

ID  Sent 
----------------- 
1  Queued 
2  Failed 
3  2013-02-28 
4  Queued 

我當前的SQL Server CE查詢:

select 
    ID, DateAdded, 
    case when DateSent is null then 
     (case when Status='W' then 'Waiting' else 
     case when Status='O' then 'Uploaded' else 
     case when Status='F' then 'Failed' else 
     case when Status='E' then 'Expired' else 
     'Unknown' end end end end) else DateSent 
    end as Sent 
from table 

else DateSent部分上線7拋出一個錯誤:

There was a syntax error in the date format. [0, 0, 0,Expression: Failed,,]

可能有人幫助我如何解決這個問題?

編輯:問題的一種更容易閱讀的片段是:

select case when DateSent is null 
then 'null' else DateSent --<---- problem is here 
end as Sent from table 
+0

是的,我的不好。我誤讀了。但你爲什麼這麼複雜?你可以用一個CASE表達式來做同樣的事情。 – 2013-02-28 16:34:09

+0

@ypercube我在一個月前開始學習SQL,所以我不太熟悉最簡單/最有效的方法:) – 2013-02-28 16:36:41

回答

2

試試這個; (您可能需要將DateSent轉換爲nvarchar)

select ID, 
     DateAdded, 
     case when DateSent is null 
      then (case status when 'W' then 'Waiting' 
           when 'O' then 'Uploaded' 
           when 'F' then 'Failed' 
           when 'E' then 'Expired' 
             else 'Unknown' 
        end) 
      else convert(nvarchar(30), DateSent) 
     end as Sent 
from table 
+0

使用此查詢,我得到錯誤:'無效參數日期編碼' - 當你說「將DateSent轉換爲varchar」 - 你的意思是轉換查詢中的輸入嗎?或者轉換列的數據類型? (我真的不想做後者) – 2013-02-28 16:41:46

+1

不是字段數據類型:)。在case的其他部分輸出datesent。在SQL服務器它是'轉換(varchar(30),datesent)'不確定關於CE語法。 – Kaf 2013-02-28 16:48:05

+0

啊哈!這工作!對於CE,它需要'nvarchar'而不是'varchar'。請添加爲答案,我會接受/ upvote :) – 2013-02-28 16:50:41