如何简化此查询?我需要将临时变量值与多行的列值进行比较

时间:2017-07-19 08:40:36

标签: sql sql-server sql-server-2008

我需要将临时变量值与多行的列值进行比较,然后根据该值执行操作。

  | intSeqID    | Value |
 ----------------------------
     1          | 779.40
     2          | 357.38
     3          |  NULL
     4          |  NULL
     5          |  NULL
     6          |  NULL
     7          |  NULL
     8          |  NULL
     9          |  NULL
    10          |  NULL

    DECLARE @tmpRange NUMERIC(5,2)
    SELECT @tmpRange = 636

这里我需要将值@tmpRange与TABLE中的Value进行比较,并根据它执行操作。

      IF((@tmpRange < (select ISNULL(Value,0) from @tableA intSeqID=1)) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=2))) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=3))) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=9))) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=10)))
       BEGIN
       SELECT 'All'
       END 
       ELSE IF ((@tmpRange < (select ISNULL(Value,0) from @tableA intSeqID=1)) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=2))) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=3))) AND 
      (@tmpRange< (select ISNULL(Value,0) from @tableA where intSeqID=9))))
          BEGIN
          SELECT '10'
          END
       END

如何简化此查询以比较值。或者是否有其他方法可以选择多行的值并将其与temp变量进行比较。

3 个答案:

答案 0 :(得分:1)

这是一种相当简单的方法:

创建并填充样本表(在将来的问题中保存此步骤)

DECLARE @tableA as table
(
    intSeqID int identity(1,1),
    Value numeric(5,2)
)

INSERT INTO @tableA VALUES
(779.40),
(357.38),
(256.32),
(NULL)

声明并填充变量:

DECLARE @tmpRange numeric(5, 2) = 636

查询:

;WITH CTE AS
(
    SELECT TOP 1 intSeqId
    FROM @TableA
    WHERE @tmpRange < ISNUll(Value, 0)
    ORDER BY Value 
) 

SELECT  CASE WHEN intSeqId = 
            (
                SELECT TOP 1 intSeqId
                FROM @TableA
                ORDER BY ISNUll(Value, 0) 
            ) THEN 'All'
       ELSE CAST(intSeqId as varchar(3))
       END 
FROM CTE

结果:1

See a live demo on rextester.

答案 1 :(得分:0)

我们可以尝试使用聚合重构您的查询。我们几乎没有子查询,除了只有一个,这是区分这两个条件所必需的。

SELECT
    CASE WHEN SUM(CASE WHEN @tmpRange < Value THEN 1 ELSE 0 END) = 4 AND
    @tmpRange < (SELECT Value FROM @tableA WHEREA intSeqID = 10)
         THEN 'All'
         WHEN SUM(CASE WHEN @tmpRange < Value THEN 1 ELSE 0 END) = 4
         THEN '10'
         ELSE 'NONE' END AS label
FROM @tableA
WHERE intSeqID IN (1, 2, 3, 9)

答案 2 :(得分:0)

你想找到Value中最大的记录,谁也小于你的变量,对吗?

--DECLARE @tableA TABLE (intSeqID tinyint, [Value] decimal(5,2))
--INSERT INTO @tableA SELECT 1, 400 UNION SELECT 2, 300 UNION SELECT 3, 200
--DECLARE @tmpRange decimal(5,2) = 250

SELECT TOP 1 *
FROM (
    SELECT TOP 1 CONCAT('', intSeqID) AS intSeqID -- Can't UNION int to varchar.
    FROM @tableA
    WHERE ISNULL([Value], 0) < @tmpRange
    ORDER BY intSeqID ASC
    UNION
    SELECT 'All' AS [?]
) AS T
ORDER BY intSeqID ASC