我使用SUM和case表达式生成2个聚合值,然后我想将2个数字除以计算百分比。
我尝试过播放所有语句,但我一直收到错误:
Msg 8117,Level 16,State 1,Line 4 操作数数据类型varchar对除运算符无效。
我很困惑,它正在读取第三个条件作为varchar - 我尝试将其转换为Integer和Decimal,但收到相同的错误。这是我正在使用的代码:
SELECT
cast(SUM(case when Patient_Ethnic_Origin_Code = '99' then 1 end) as INTEGER)'Not Known'
, cast(SUM(case when Patient_Ethnic_Origin_Code IS NOT NULL then 1 end)as INTEGER)'All'
, cast('Not Known'/'All' as DECIMAL (10,2)) 'Calculation'
我也尝试过使用不同的方法,但这也会产生同样的错误:
SELECT
'NotKnown'
,'All'
,'NotKnown' / 'All' as 'Calculation'
(SELECT
cast(SUM(case when Patient_Ethnic_Origin_Code = '99' then 1 end) as INTEGER)as 'NotKnown'
, cast(SUM(case when Patient_Ethnic_Origin_Code IS NOT NULL then 1 end)as INTEGER)as 'All'
FROM Inpatients.vw_IP_Spells
WHERE Discharge_Date BETWEEN '01/01/2017' AND '31/01/2017'
AND Admission_Method_National_Code LIKE '2%'
AND Patient_Ethnic_Origin_Code != 'Z'
)
任何人都可以建议我的语法出错吗?
答案 0 :(得分:0)
您不能在该子句中再次使用SELECT
子句中的别名。我也认为你不需要那些演员阵容。这样的事情应该有效:
SELECT
SUM(CASE WHEN Patient_Ethnic_Origin_Code = '99' THEN 1 END) AS [Not Known],
SUM(CASE WHEN Patient_Ethnic_Origin_Code IS NOT NULL THEN 1 END) AS [All],
CAST(SUM(CASE WHEN Patient_Ethnic_Origin_Code = '99' THEN 1 END) AS DECIMAL(10,2)) /
SUM(CASE WHEN Patient_Ethnic_Origin_Code IS NOT NULL THEN 1 END) [Calculation]
FROM Inpatients.vw_IP_Spells
WHERE ...
你的第二次尝试,也可能是一个好主意,但失败了,因为你指的是使用字符串文字的别名,即
'NotKnown' / 'All' as 'Calculation'
SQL Server认为您正在尝试划分字符串,因此您看到的错误。如果您想沿着包含子查询的包装路线前进,可以尝试以下操作:
SELECT t.[Not Known],
t.[All],
CAST(t.[Not Known] AS DECIMAL(10,2)) / t.[All] AS [Calculation]
FROM
(
SELECT
SUM(CASE WHEN Patient_Ethnic_Origin_Code = '99' THEN 1 END) AS [Not Known],
SUM(CASE WHEN Patient_Ethnic_Origin_Code IS NOT NULL THEN 1 END) AS [All],
FROM Inpatients.vw_IP_Spells
WHERE ...
) t
这样做的另一个好处是可以使整个查询更简洁,更容易阅读。它也可能会降低性能,但也许你并不关心它。