SQL无效的列名称 - WHERE子句中的计算条件

时间:2016-12-15 16:22:42

标签: sql sql-server

我有以下查询:

SELECT ImgHeight, ImgWidth,
 IIF(ImgHeight > ImgWidth, ImgHeight, ImgWidth) as imgMaxSize
 FROM Images
WHERE imgMaxSize > 100

但我收到消息:

  

列名'imgMaxSize'无效。

我可以将条件复制如下,但计算最大值两次似乎没有效果。

SELECT Img1Height,
 Img1Width,
 IIF(Img1Height > Img1Width, Img1Height, Img1Width) as imgMaxSize
 From Realty
where IIF(Img1Height > Img1Width, Img1Height, Img1Width) > 100

这里推荐的方法是什么?

2 个答案:

答案 0 :(得分:3)

在SQL Server中,您可以使用outer apply

SELECT i.ImgHeight, i.ImgWidth, v.imgMaxSize
FROM Images i OUTER APPLY
     (VALUES(CASE WHEN i.ImgHeight > i.ImgWidth THEN i.ImgHeight ELSE i.ImgWidth END)
     ) v(imgMaxSize)
WHERE v.imgMaxSize > 100;

当然,CTE和子查询也解决了这个问题;我就像使用横向连接一样。

或者:

SELECT i.ImgHeight, i.ImgWidth,
       (CASE WHEN i.ImgHeight > i.ImgWidth THEN i.ImgHeight ELSE i.ImgWidth END) as imgMaxSize
FROM Images i 
WHERE i.ImgHeight > 100 or i.ImgWidth > 100;

我应该补充一点,除非有充分的理由使用其他东西,否则我也非常偏向ANSI标准语法。因此,outer apply有充分的理由。 IIF()代替CASE不是一个好理由。

答案 1 :(得分:1)

此:

select * from (
    SELECT ImgHeight, ImgWidth,
        IIF(ImgHeight > ImgWidth, ImgHeight, ImgWidth) as imgMaxSize
    FROM Images
    ) as i
WHERE imgMaxSize > 100

或者:

with cte as (
    SELECT ImgHeight, ImgWidth,
        IIF(ImgHeight > ImgWidth, ImgHeight, ImgWidth) as imgMaxSize
    FROM Images
);

select * from cte
WHERE imgMaxSize > 100
相关问题