SQL Server:选择一些东西作为' VARIABLE'

时间:2016-03-10 23:46:00

标签: sql sql-server database

我做了SELECT的事情' VARIABLE',像这样

SELECT  
    SUM(CASE WHEN BA_Idx = 503 THEN BIL_Debit ELSE 0 END) AS 'SUM_DEBIT_503',
    SUM(CASE WHEN BA_Idx = 504 THEN BIL_Debit ELSE 0 END) AS 'SUM_DEBIT_504'
FROM    
    Bill
WHERE   
    (@MEM_Idx = 0 OR MEM_Idx = @MEM_Idx) AND
    (LEFT(BIL_YYMMDD,7) = @BILM_YYMM) AND           
    BIL_IsValid = 'True'

SELECT @BILFC_TotalLaborCost = SUM_DEBIT_503 + SUM_DEBIT_504

我想接近VARIABLE(' SUM_DEBIT_503',' SUM_DEBIT_504' )来计算@BILFC_TotalLaborCost

我该如何处理?

2 个答案:

答案 0 :(得分:1)

SELECT本身进行作业:

SELECT @BILFC_TotalLaborCost =
    SUM(CASE WHEN BA_Idx = 503 THEN BIL_Debit ELSE 0 END) +
    SUM(CASE WHEN BA_Idx = 504 THEN BIL_Debit ELSE 0 END)
FROM Bill
WHERE
    (@MEM_Idx = 0 OR MEM_Idx = @MEM_Idx)
    AND (LEFT(BIL_YYMMDD, 7) = @BILM_YYMM)
    AND BIL_IsValid = 'True'

答案 1 :(得分:1)

您可以在查询中设置变量。这样,如果你需要它们,它们可以在以后使用。

DECLARE @SumDebit503 <SOMETYPE>
DECLARE @SumDebit504 <SOMETYPE>

SELECT @SumDebit503 = SUM(CASE WHEN BA_Idx = 503 THEN BIL_Debit ELSE 0 END),
       @SumDebit504 = SUM(CASE WHEN BA_Idx = 504 THEN BIL_Debit ELSE 0 END)
FROM Bill
WHERE
    (@MEM_Idx = 0 OR MEM_Idx = @MEM_Idx)
    AND (LEFT(BIL_YYMMDD, 7) = @BILM_YYMM)
    AND BIL_IsValid = 'True'

SELECT  @BILFC_TotalLaborCost = @SumDebit503 + @SumDebit504