选择具有最小值的行,同时获得“大于1个值”错误?

时间:2018-12-08 23:12:08

标签: sql-server tsql common-table-expression

我想做这样的事情:

    select * from challenger 
        where sqrt( square(Launch_temperature-70) )=
   ( select min( sqrt( square(Launch_temperature-70) ) ) 
        from challenger)

但是如果我在下面使用其他两种方式,SQL Server 2017会给我这种错误消息:

  

子查询返回了多个值。当   子查询遵循=,!=,<,<=,>,> =,或当子查询用作   表达式。

with cte(value) 
as
(
    select sqrt(square(Launch_temperature- 70)) as value 
    from challenger
)
select  * from challenger 
order by 
(select value from cte) ASC;

select  * from challenger 
    order by 
(select sqrt(square(Launch_temperature-70)) from challenger) ASC;

那是为什么?反正要解决这个问题吗?

编辑:我找到了解决方法! 一种方式:

select top 1 * from challenger 
order by 
abs(Launch_temperature-70) ASC

另一种方式:

with cte(value) 
as
(
    select sqrt(square(Launch_temperature- 70)) as value 
    from challenger
)

select  top 1 * from challenger, cte 
order by 
(value) ASC;

1 个答案:

答案 0 :(得分:1)

如果您在cte中执行计算,请重新使用该cte

WITH cte
AS (
    SELECT
          *
        , SQRT( SQUARE( Launch_temperature - 70 ) ) AS value
    FROM challenger
)
SELECT
    *
FROM cte
WHERE value = (SELECT MIN( value ) FROM cte)
ORDER BY
    value

现在您将ABS(Launch_temperature)视为要求,另一种方法是:

SELECT
    *
FROM (
    SELECT
        *
      , ROW_NUMBER() OVER (ORDER BY ABS( Launch_temperature )) AS rn
    FROM challenger
) AS d
WHERE rn = 1