我在SQL中执行此查询但是给出了这样的错误“无法对包含聚合或子查询的表达式执行聚合函数”。是否有人可以帮助我。我真的被卡住了。谢谢 这是我的查询。
SELECT [id]
,[name]
,SUM(case
when [code] = 1 Then
case
when exists(select * from [sampletab] where [id] = [id]and [code] = 2) then
case when exists(select * from [sampletab] where [id] = [id] and [code] = 4) then 100
else 100
end
else 100
end
when [code] = 8 then 200
when code = 2 then 100
when code = 4 then 100
end
) as "totl"
FROM [test].[dbo].[sampletab]
GROUP BY id , name
答案 0 :(得分:0)
这是您的查询版本,实际上应该获得一些结果。
SELECT
Id,
Name,
SUM(ScorePerCode)
FROM (
SELECT
id,
name,
CASE WHEN code = 1 THEN 100
WHEN code = 2 THEN 50
WHEN code = 4 THEN 20
WHEN code = 8 THEN 200
END AS ScorePerCode
FROM [test].[dbo].[sampletab]
) X
GROUP BY Id, Name
您的查询的这一部分毫无意义,是您问题的根源。如果此查询有机会工作,您总是会达到100的值...
WHEN [code] = 1
THEN
CASE WHEN EXISTS ( SELECT * FROM [sampletab] WHERE [code] = 2 )
THEN
CASE WHEN EXISTS ( SELECT * FROM [sampletab] WHERE [code] = 4)
THEN 100
ELSE 100 END
ELSE 100 END