如何将子查询结果存储在变量中并在主查询中使用

时间:2014-10-28 05:59:29

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

我需要将subquery结果存储在变量中并用于主查询以节省查询的执行时间,否则我必须再次写入相同的subquery。代码如下:

select DISTINCT
convert(datetime,substring(o.TransactTime, 0,9), 112) + CONVERT(datetime, substring(o.transacttime,10,LEN(o.transacttime)), 114),
o.clordid,
ack.strategyid,
o.Account, 
o.AllocAccount, 
o.symbol,
o.price,
ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty) orderqty,

o.InClOrdID,
(SELECT  ISNULL(ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty)-sum(ex.LastShares),ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty)) from order_msgs_incoming<TblIndx> ex where
    o.Clordid = ex.clordid 
) RemainingQuantity
from order_msgs_incoming1 o 
/*picking ack rows to update strategyId since StrategyId is null for 43 but populated for 46*/
left outer join order_msgs_incoming1 ack on o.clordid = ack.clordid and ack.msg_id=46
where 
/*row for new order only since that contains all columns values*/
o.msg_id = 43

我需要这样

select DISTINCT
variableValue=ISNULL((Select Top 1 L.orderqty from order_msgs_incoming1 L where o.clordid=L.clordid and L.msg_id in (17,18,19,22,59,44) order BY L.transacttime DESC),o.orderqty) orderqty,

o.InClOrdID,
(SELECT  ISNULL(variableValue-sum(ex.LastShares),variableValue) from order_msgs_incoming<TblIndx> ex where
    o.Clordid = ex.clordid 
) RemainingQuantity
from order_msgs_incoming1 o 

请帮帮我。

1 个答案:

答案 0 :(得分:0)

您可以使用SELECT子句声明变量并为其赋值。然后在主查询中使用该变量。请找到以下代码:

DECLARE @variableValue bit;

SELECT @variableValue = ISNULL(
                        (
                        SELECT TOP 1 L.orderqty 
                        FROM order_msgs_incoming1 L 
                        WHERE o.clordid=L.clordid
                        AND L.msg_id in (17,18,19,22,59,44) 
                        ORDER BY L.transacttime DESC
                        )
                        ,o.orderqty
                    )
FROM order_msgs_incoming1 o

SELECT DISTINCT
@variableValue AS orderqty,
o.InClOrdID,
(
    SELECT  ISNULL(variableValue-sum(ex.LastShares)
    ,variableValue) 
    FROM order_msgs_incoming<TblIndx> ex 
    WHERE o.Clordid = ex.clordid 
) RemainingQuantity
FROM order_msgs_incoming1 o 

您还可以使用以下代码更改子查询,以便可以在变量中使用它:

SELECT TOP 1 L.orderqty 
FROM order_msgs_incoming1 L 
INNER JOIN order_msgs_incoming1 o 
    ON o.clordid=L.clordid
    AND L.msg_id in (17,18,19,22,59,44) 
ORDER BY L.transacttime DESC