我有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
答案 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...)