我有一个贷款记录可能有5个余额字段。我需要总计这些字段,同时排除包含特定代码的每个贷款记录的列。
以下是数据记录的示例,每个总字段都有相应的代码。我想总结所有总数并排除" X"代码总数。 代码" X"可以附加到任何总列,在这种情况下它恰好在最后。
loan number | total 1 | total 2 | total 3 | total 4 |total 5 | code1 | code2 | code3 | code4 | code5
123456789 | 12.50 | 1,950.43 | 750.00 | | 275.98 | A | B | C | | X
这是现有TSQL查询中的子查询:
, (SELECT [CMI ACCOUNT],
[Unapplied Funds 1 - Balance] = SUM (CASE WHEN [UNAPPLIED code 1] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 1], 0) end
+ CASE WHEN [UNAPPLIED code 2] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 2], 0) end
+ CASE WHEN [UNAPPLIED code 3] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 3], 0) end
+ CASE WHEN [UNAPPLIED code 4] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 4], 0) end
+ CASE WHEN [UNAPPLIED code 5] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 5], 0) end)
FROM CIT_UNAPPLIED
GROUP BY [CMI ACCOUNT]
)
不幸的是,这给了我一条错误信息:
当EXISTS没有引入子查询时,只能在选择列表中指定一个表达式。
答案 0 :(得分:0)
错误消息表明子查询位于Select列表或WHERE子句
中它应该是from
的一部分SELECT
b.[CMI ACCOUNT],
b.[Unapplied Funds 1 - Balance]
FROM
(
SELECT [CMI ACCOUNT],
[Unapplied Funds 1 - Balance] = SUM (CASE WHEN [UNAPPLIED code 1] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 1], 0) end
+ CASE WHEN [UNAPPLIED code 2] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 2], 0) end
+ CASE WHEN [UNAPPLIED code 3] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 3], 0) end
+ CASE WHEN [UNAPPLIED code 4] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 4], 0) end
+ CASE WHEN [UNAPPLIED code 5] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 5], 0) end
FROM CIT_UNAPPLIED
GROUP BY [CMI ACCOUNT]
) b
您可以像使用普通表一样将子查询加入其他表,视图或子查询
SELECT
a.[Account Name],
b.[CMI ACCOUNT],
b.[Unapplied Funds 1 - Balance]
FROM
Another Table a
JOIN
(
SELECT [CMI ACCOUNT],
[Unapplied Funds 1 - Balance] = SUM (CASE WHEN [UNAPPLIED code 1] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 1], 0) end
+ CASE WHEN [UNAPPLIED code 2] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 2], 0) end
+ CASE WHEN [UNAPPLIED code 3] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 3], 0) end
+ CASE WHEN [UNAPPLIED code 4] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 4], 0) end
+ CASE WHEN [UNAPPLIED code 5] = 'L' THEN 0 ELSE ISNULL( [UNAPPLIED BALANCE 5], 0) end
FROM CIT_UNAPPLIED
GROUP BY [CMI ACCOUNT]
) b
ON a.[CMI ACCOUNT]=b.[CMI ACCOUNT]
取决于您希望其余查询执行的操作