在select语句的WHERE子句中使用动态列

时间:2020-03-10 14:03:13

标签: sql sql-server

我有这个查询:

select 
    *
    ,(select location from [order] where [id] = oi.OrderID) as orderlocation
    ,case 
        when oi.location is not null then oi.location
        when oi.location is null then orderlocation
        end
from
    orderitem oi

我得到一个错误:

无效的列名'orderlocation'

以下查询可以正常工作,并且可以完成预期的工作:

select  
    *
    ,(select location from [order] where [id] = oi.OrderID) as orderlocation
    ,case 
        when oi.location is not null then oi.location
        when oi.location is null then (select location from [order] where [id] = oi.OrderID)
        end
from
    orderitem oi

实际上,这不是一个巨大的问题,但是必须重复两次相同的文本,并且要记住,如果它改变了,则必须记住在两个地方都进行更新,这有点麻烦。有没有更好的方式来编写此查询,以便没有重复?也许使用变量之类的东西?我不是SQL专家,所以我不确定写这个的更好方法。

任何帮助将不胜感激。预先感谢!

3 个答案:

答案 0 :(得分:3)

您可以将子查询移至FROM

select *, --This should really be a proper list
       ISNULL(oi.location,ol.orderlocation) AS OrderLocation2 --ISNULKL or COALESCE are much more succinct
from orderitem oi
     CROSS APPLY (select location AS orderlocation from [order] o where o.[id] = oi.OrderID)) o; --Use OUTER APPLY if this may not return a result

尽管查看您的代码,但这不是真的吗:

SELECT oi.*, --still should be a distinct column list
       o.location,
       ISNULL(oi.location,o.location ) AS OrderLocation
FROM dbo.orderitem oi
     JOIN dbo.[order] O ON o.[id] = oi.OrderIDl --LEFT JOIN if there may not be a row here.

答案 1 :(得分:1)

扩展@John Cappelletti的评论。

select *
    ,ord.location  as orderlocation
    ,case 
        when oi.location is not null then oi.location
        when oi.location is null then ord.location
        end
from orderitem oi
LEFT JOIN [order] ORD on ord.[id] = oi.OrderID

答案 2 :(得分:0)

我实际上已经在使用联接,但是我简化了该问题的查询。带有case语句的原始查询为

select * from orderitem oi inner join [order] o on oi.orderid = o.id

但是,我不知道合并或isull命令。他们工作得很好。我结束了:

select *
   ,coalesce(oi.location, o.location) as ManufacturingLocation
from orderitem oi inner join [order] o
on oi.orderid = o.id

感谢您的帮助!

相关问题