我如何避免一遍又一遍地调用相同的sql语句

时间:2013-03-11 18:35:10

标签: sql sql-server-2008

我有sql声明

SELECT coalesce((Select sum(SomeNumber) 
FROM Table 
WHERE ID NOT IN (SELECT IDs...)), 0) MyFirstNumber,
coalesce((Select sum(SomeNumber2) 
FROM Table 
WHERE ID NOT IN (SELECT IDs...)), 0) MySecondNumber

如何才能使(SELECT IDs...)查询语句只调用一次,比如上面的语句之前。

我认为它会像

DECLARE @MyIDs
SET @MyIDs = SELECT IDs FROM TABLE WHERE ...

SELECT coalesce((Select sum(SomeNumber) 
FROM Table 
WHERE ID NOT IN (@MyIDs)), 0) MyFirstNumber,
coalesce((Select sum(SomeNumber2) 
FROM Table 
WHERE ID NOT IN (@MyIDs)), 0) MySecondNumber

2 个答案:

答案 0 :(得分:1)

如何加入该子选择并仅过滤连接为假的位置(返回null)

SELECT sum(coalesce(SomeNumber,0)) MyFirstNumber
       ,sum(coalesce(SomeNumber2,0)) MySecondNumber
FROM   Table 
       LEFT JOIN (SELECT IDs.. FROM Table ) AS Filter ON Table.ID = Filter.ID
WHERE  Filter.ID IS NULL

答案 1 :(得分:0)

在一个SELECT语句中计算金额

SELECT COALESCE(SUM(SomeNumber), 0) AS MyFirstNumber, 
       COALESCE(SUM(SomeNumber2), 0) AS MySecondNumber
FROM Table
WHERE ID NOT IN (SELECT IDs FROM TABLE WHERE...)

如果需要不同的条件,可以在SUM()函数

中使用CASE表达式
SELECT COALESCE(SUM(SomeNumber), 0) AS MyFirstNumber, 
       COALESCE(SUM(SomeNumber2), 0) AS MySecondNumber,
       COALESCE(SUM(CASE WHEN ... THEN SomeNumber3 END), 0) AS MyThirdNumber
FROM Table
WHERE ID NOT IN (SELECT IDs FROM TABLE WHERE...)