SQL - 将聚合表与非聚合表连接起来
Posted
技术标签:
【中文标题】SQL - 将聚合表与非聚合表连接起来【英文标题】:SQL - JOIN AN AGGREGATE TABLE WITH A NONAGGREGATE TABLE 【发布时间】:2015-02-20 11:39:14 【问题描述】:我编写了以下代码,用于从每笔贷款中选择总的剩余利息支付:
SELECT a.PARENTREF, a.INTEREST - Isnull(b.INTEREST,0) AS INTEREST FROM (SELECT PARENTREF, SUM(TOTAL) AS INTEREST FROM LG_011_BNCREPAYTR WHERE TRANSTYPE = 0 GROUP BY PARENTREF) a LEFT OUTER JOIN (SELECT PARENTREF, SUM(TOTAL) AS INTEREST FROM LG_011_BNCREPAYTR WHERE TRANSTYPE = 1 GROUP BY PARENTREF) b ON a.PARENTREF = b.PARENTREF
它带来了如下表格:
PARENTREF INTEREST 1 500.93 2 510.00 3 1200.90 4 500.93
现在,数据库中有另一个表,其中包含有关贷款的其他信息,例如贷款描述。该表的LOGICALREF
就是该表中的PARENTREF
。该表如下:
LOGICALREF DESCRIPTION CURRENCYREF DUEDATE 1 CAR LOAN 0 2015-10-01 2 CONSUMER LOAN 2 2015-10-01 3 CAR LOAN 4 2015-10-01 4 CAR LOAN 3 2015-10-01
我正在尝试将我的表与我提到的最后一个表结合起来,但由于某种原因,我得到了 DESCRIPTION
、CURRENCYREF
和 DUEDATE
作为 NULL
。我认为由于我使用的GROUP BY
存在问题,因为如果我不聚合,这些功能就会起作用。我想要的表格如下:
PARENTREF INTEREST DESCRIPTION CURRENCYREF DUEDATE 1 500.93 CAR LOAN 0 2015-10-01 2 510.00 CONSUMER LOAN 2 2015-10-01 3 1200.90 CAR LOAN 4 2015-10-01 4 500.93 CAR LOAN 3 2015-10-01
非常感谢。
【问题讨论】:
【参考方案1】:试试这个:
SELECT a.PARENTREF, a.INTEREST - ISNULL(b.INTEREST, 0) AS INTEREST,
T.DESCRIPTION, T.CURRENCYREF, T.DUEDATE
FROM YourTable T
INNER JOIN (SELECT PARENTREF, SUM(TOTAL) AS INTEREST
FROM LG_011_BNCREPAYTR
WHERE TRANSTYPE = 0
GROUP BY PARENTREF) A ON T.LOGICALREF = A.PARENTREF
LEFT OUTER JOIN (SELECT PARENTREF, SUM(TOTAL) AS INTEREST
FROM LG_011_BNCREPAYTR
WHERE TRANSTYPE = 1
GROUP BY PARENTREF
) b ON a.PARENTREF = b.PARENTREF;
或
您也可以使用以下查询找到解决方案
SELECT A.PARENTREF,
(SUM(CASE WHEN A.TRANSTYPE = 0 THEN A.TOTAL ELSE 0 END) - SUM(CASE WHEN A.TRANSTYPE = 1 THEN A.TOTAL ELSE 0 END)) AS INTEREST,
T.DESCRIPTION, T.CURRENCYREF, T.DUEDATE
FROM YourTable T
INNER JOIN LG_011_BNCREPAYTR A ON T.LOGICALREF = A.PARENTREF
GROUP BY A.PARENTREF;
【讨论】:
以上是关于SQL - 将聚合表与非聚合表连接起来的主要内容,如果未能解决你的问题,请参考以下文章