我试图根据活动预订制作一张桌子。人们预定自己参加活动,并指定他们将携带多少客人。
我希望表格中的每一行分别列在列中:预订,此人携带的客人人数,以及预订+客人的总和(实际上,此第三列将为否客人+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。这是错误消息:
Msg 245,Level 16,State 1,Line 1
转换varchar值时,转化失败'当前预订' 数据类型int。
如何将此转换为CASE
语句中的整数,然后这会使最终列的总和为每行的总和?
感谢任何指导。
答案 0 :(得分:2)
SUM
是一个set函数,只需执行+
即可在一行内求和。 (但你不能在那里使用列别名。)
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'
答案 1 :(得分: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'