T SQL-将一个查询的结果用作其他查询的变量

时间:2012-10-08 14:29:19

标签: sql sql-server tsql

我写过这个查询;我需要帮助分配变量;这是来自其他查询,我该怎么做。

我如何将它们组合在一起?

查询1

Select SUM(Credit)
FROM(SELECT TOP 1  Credit
FROM (SELECT DISTINCT TOP 2 Ref, Credit, PaymentID 
FROM  Payment where  Ref =  '????'  AND PaymentID <= '????' 
ORDER BY PaymentID DESC)
a ORDER BY PaymentID)
b

查询2

Select Ref, PaymentID 
From Payment
Where PaymentDate = '2012-09-23'

所以我需要查询2的Ref和PaymentID,并在查询1中用作变量

3 个答案:

答案 0 :(得分:2)

使用联接

SELECT DISTINCT TOP 2 Ref, Credit, PaymentID      
FROM  Payment 
    inner join
    (Select Ref, PaymentID  From Payment Where PaymentDate = '2012-09-23' ) query2
        on Payment.Ref = query2.Ref and Payment.PaymentID <= query2.PaymentID      
ORDER BY PaymentID DESC

答案 1 :(得分:0)

宣布@yourvar

选择@yourvar = SUM(Credit)....

答案 2 :(得分:0)

您可以将所需的字段声明为变量:

DECLARE @REF        varchar(20)
DECLARE @PaymentID  int

SET @REF =  (Select Ref
                From Payment
                Where PaymentDate = '2012-09-23')

SET @PaymentID =    (Select PaymentID
                    From Payment
                    Where PaymentDate = '2012-09-23')

Select  SUM(Credit)
FROM(SELECT TOP 1  Credit
FROM (SELECT DISTINCT TOP 2 Ref, Credit, PaymentID 
FROM  Payment where  Ref IN(@REF)  AND PaymentID <= @PaymentID
ORDER BY PaymentID DESC)
a ORDER BY PaymentID)
b

编辑:我猜测PaymentID是INT,Ref是varchar字段。您可以在声明语句中更改其他数据类型。