如何进行这样的查询?
SELECT
PersonId,
Name,
(
DECLARE @p INT=(SELECT (Not1 + Not2 + Not3)/3 FROM Tablo_Not WHERE NotId=PersonId);
DECLARE @s INT;
IF @p>84
SET @s=5;
ELSE IF @p>69
SET @s=4;
ELSE IF @p>54
SET @s=3;
ELSE IF @p>44
SET @s=2;
ELSE
SET @s=1;
SELECT @s;
) AS Degree
FROM Tablo_Person;
您不能在这样的
DECLARE
查询中使用 SELECT
语句。但是,您可以通过使用 CASE
表达式而不是 DECLARE
和 IF
语句来实现结果。
SELECT
PersonId,
Name,
CASE
WHEN (SELECT (Not1 + Not2 + Not3)/3 FROM Tablo_Not WHERE NotId = PersonId) > 84 THEN 5
WHEN (SELECT (Not1 + Not2 + Not3)/3 FROM Tablo_Not WHERE NotId = PersonId) > 69 THEN 4
WHEN (SELECT (Not1 + Not2 + Not3)/3 FROM Tablo_Not WHERE NotId = PersonId) > 54 THEN 3
WHEN (SELECT (Not1 + Not2 + Not3)/3 FROM Tablo_Not WHERE NotId = PersonId) > 44 THEN 2
ELSE 1
END AS Degree
FROM Tablo_Person;