我正在编写一个查询来汇总一个事件的预订,然后将总数分成两个类别:一个有应用程序的人数和一个没有应用程序的人数。
计算总预订数量和申请人数量没问题 - 我使用的代码如下:
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...
但是,我在计算没有申请的人数方面遇到了问题(即他们没有与其帐户相关的申请记录)。我尝试过使用NOT EXISTS语句,但发现这在聚合语句中不起作用。
所以,我试图做的只是从'总预订'数字中减去'申请人数',因为这将留给非申请人数的计数。
我尝试使用以下代码行简单地减去上述两个输出:
SUM ('Total Bookings' - 'Current Applicants') 'Non-Applicants'
但这给了我错误:
"Msg 8117, Level 16, State 1, Line 4
Operand data type varchar is invalid for subtract operator."
我假设我需要将早期输出转换为整数 - 请任何人都可以帮我解释语法吗?
答案 0 :(得分:1)
您无法在同一查询中直接使用计算中的列别名,您可以将当前Hibernate: select user0_.id as id1_0_, user0_.name as name2_0_, user0_.since as since3_0_, user0_.until as until4_0_ from user user0_ where user0_.since>? and user0_.until<?
用作派生表或CTE,或者只是派生新计算。此外,您应该避免对表别名使用单引号,而是使用SELECT
:
[]
答案 1 :(得分:0)
使用 Square Brackets 来转义列名称中的空格。单引号将使其成为字符串常量
select SUM ([Total Bookings] - [Current Applicants]) 'Non-Applicants'
from
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants'
..
)
注意:当您使用单引号转义别名中的空格时,它会起作用,但在将其用作列名时不起作用
答案 2 :(得分:0)
试试这个:
SELECT * , [Non-Applicants] = [Total Bookings] - [Current Applicants]
FROM
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end) 'Current Applicants' ...
) A
答案 3 :(得分:0)
希望这有帮助
with cte as
(
SELECT [EVENTMODULE].[DESCRIPTION] as 'Event', cast([EVENTMODULE].[STARTDATE] as date) as 'Event Date',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') then 1 else 0 end) 'Total Bookings',
SUM (case when [EVENTPLACE].[STATUS] IN ('Accepted','Attended') AND [COURSEPLACE].[TYPE] = 'Application' then 1 else 0 end)
)
select Event,Event Date,Total Bookings,[Total Bookings]-[EVENTPLACE].[STATUS] AS 'Non-Applicants'
from cte