2016-07-28 50 views
0

我正試圖根據事件的預訂來生成表格。人們將自己預訂到活動中,並指定他們將帶來多少客人。如何將CASE varchar轉換爲INT,以便我可以對一行進行求和?

我希望表格中的每一行在列中分別列出:預訂,此人帶來的客人數量,然後是預訂+客人總數(實際上,第三列將是客人數+1)。

SELECT 'Open day' Event, 
     CASE WHEN BOOKINGSTATUS = 'Booked' THEN 1 ELSE 0 END as 'Current Bookings', 
     GUESTS as 'Number of Guests', 
     SUM ('Current Bookings'+'Number of Guests') as 'Total: Booking & Guests' 
WHERE EVENTID = 'xxxxx-111111-22222-xxxxx' 

我得到的問題是'當前預訂'列中的'1'值顯然是一個VARCHAR。這裏的錯誤消息:

消息245,級別16,狀態1,行1個

轉換轉換VARCHAR值 '當前預約' 爲int數據類型時失敗。

如何將其轉換爲CASE語句中的整數,然後這將啓用最後一列總計爲每行的總和?

感謝您的任何指導。

+0

的可能的複製[TSQL - 施法字符串爲整數或返回默認值(http://stackoverflow.com/questions/2000045/tsql-cast-字符串到整數或返回默認值) – NEER

回答

2

SUM是一組功能,只需做+而不是行內總結。 (但你不能使用列別名那裏。)

SELECT 'Open day' Event, 
     CASE WHEN BOOKINGSTATUS = 'Booked' THEN 1 ELSE 0 END as 'Current Bookings', 
     GUESTS as 'Number of Guests', 
     CASE WHEN BOOKINGSTATUS = 'Booked' THEN 1 ELSE 0 END + GUESTS as 'Total: Booking & Guests' 
WHERE EVENTID = 'xxxxx-111111-22222-xxxxx' 
+0

完美 - 這很好。非常感謝。 – Jon295087

0

請嘗試

SELECT 
    'Open day' Event, 
    CASE WHEN BOOKINGSTATUS = 'Booked' THEN 1 ELSE 0 END as 'Current Bookings', 
    GUESTS as 'Number of Guests', 
    SUM (CASE WHEN BOOKINGSTATUS = 'Booked' THEN 1 ELSE 0 END + GUESTS) as 'Total: Booking & Guests' 
WHERE EVENTID = 'xxxxx-111111-22222-xxxxx' 
相關問題