也许这是一个简单的问题,但我不知道该怎么做。 我有2个SQL查询,两者几乎相同,仅在WHERE子句中有所不同。 每个查询返回1个SUM编号。 我需要从两个查询中获取结果,并使用它来创建1个称为“ RESULT”的列,该列将计算查询的结果。
1个查询:
SELECT SUM(a.ACC_NOMINAL_AMOUNT) AS RESULT
FROM ACCOUNTS a
INNER JOIN PARTIES p
ON a.PT_KEY = p.PT_KEY
INNER JOIN ACCOUNT_COLLATERALS c
ON c.ACC_KEY = a.ACC_KEY
INNER JOIN COLLATERALS co
on c.COLT_KEY = co.COLT_KEY
INNER JOIN COLLATERAL_PORTFOLIOS por
ON co.COLTPTF_KEY = por.COLTPTF_KEY
WHERE co.COLTPTF_KEY = '261' AND
co.COLT_DELETED_FLAG = 'N' AND
a.ACC_CLOSE_FLAG = 'N'
AND co.COLT_SHORTENING_COEFFICIENT = 82
2个查询:
SELECT SUM(a.ACC_NOMINAL_AMOUNT) AS RESULT
FROM ACCOUNTS a
INNER JOIN PARTIES p
ON a.PT_KEY = p.PT_KEY
INNER JOIN ACCOUNT_COLLATERALS c
ON c.ACC_KEY = a.ACC_KEY
INNER JOIN COLLATERALS co
on c.COLT_KEY = co.COLT_KEY
INNER JOIN COLLATERAL_PORTFOLIOS por
ON co.COLTPTF_KEY = por.COLTPTF_KEY
WHERE co.COLTPTF_KEY = '261' AND
co.COLT_DELETED_FLAG = 'Y' AND
a.ACC_CLOSE_FLAG = 'Y'
AND co.COLT_SHORTENING_COEFFICIENT = 82
让我们说第一个查询返回SUM值10,第二个返回5。 因此,我需要查询将返回带有15的RESULT列。
也许编写此查询有更有效的方法,因为它仅在两个参数的WHERE子句中有所不同。
感谢帮助
答案 0 :(得分:1)
您可以轻松组合条件:
SELECT SUM(a.ACC_NOMINAL_AMOUNT)
FROM . . .
WHERE co.COLTPTF_KEY = '261' AND
co.COLT_SHORTENING_COEFFICIENT = 82 AND
(co.COLT_DELETED_FLAG, a.ACC_CLOSE_FLAG) IN ( ('N', 'N'), ('Y', 'Y') )
答案 1 :(得分:1)
这应该可以完成工作:
SELECT SUM(a.ACC_NOMINAL_AMOUNT) AS RESULT
FROM ACCOUNTS a
INNER JOIN PARTIES p ON a.PT_KEY = p.PT_KEY
INNER JOIN ACCOUNT_COLLATERALS c ON c.ACC_KEY = a.ACC_KEY
INNER JOIN COLLATERALS co ON c.COLT_KEY = co.COLT_KEY
INNER JOIN COLLATERAL_PORTFOLIOS por ON co.COLTPTF_KEY = por.COLTPTF_KEY
WHERE
co.COLTPTF_KEY = '261'
AND (a.ACC_CLOSE_FLAG, co.COLT_DELETED_FLAG) IN ( ('Y', 'Y'), ('N', 'N') )
AND co.COLT_SHORTENING_COEFFICIENT = 82
您可以使用条件聚合一次获得3个结果:
SELECT
SUM(CASE WHEN a.ACC_CLOSE_FLAG = 'N' AND co.COLT_DELETED_FLAG = 'N'
THEN a.ACC_NOMINAL_AMOUNT END) AS RESULT_N,
SUM(CASE WHEN a.ACC_CLOSE_FLAG = 'Y' AND co.COLT_DELETED_FLAG = 'Y'
THEN a.ACC_NOMINAL_AMOUNT END) AS RESULT_Y,
SUM(a.ACC_NOMINAL_AMOUNT) AS RESULT
FROM ACCOUNTS a
INNER JOIN PARTIES p ON a.PT_KEY = p.PT_KEY
INNER JOIN ACCOUNT_COLLATERALS c ON c.ACC_KEY = a.ACC_KEY
INNER JOIN COLLATERALS co ON c.COLT_KEY = co.COLT_KEY
INNER JOIN COLLATERAL_PORTFOLIOS por ON co.COLTPTF_KEY = por.COLTPTF_KEY
WHERE
co.COLTPTF_KEY = '261'
AND (a.ACC_CLOSE_FLAG, co.COLT_DELETED_FLAG) IN ( ('Y', 'Y'), ('N', 'N') )
AND co.COLT_SHORTENING_COEFFICIENT = 82