使用 if 查询并声明

问题描述 投票:0回答:1

如何进行这样的查询?

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;
sql sql-server declare iif
1个回答
0
投票

您不能在这样的

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;
© www.soinside.com 2019 - 2024. All rights reserved.