处理内部联接和值的Oracle SQL查询

时间:2017-08-02 17:57:59

标签: sql oracle

    SELECT  sc.TAAC_SHARE_CLASS_ID,
    SCS.SHARE_CLASS_SID,
    SCS.REPORTING_DT,
    SCS.SHARE_CLASS_SNAPSHOT_SID, 
    SCS.DIST_UNMOD_30_DAY_YIELD_PCT, 
    SCS.DER_DIST_12_MO_YIELD_PCT, 
    SCS.DER_SEC_30_DAY_YIELD_PCT AS SCS_DER_SEC_30_DAY_YIELD_PCT, 
    SCS.DER_SEC_RESTATED_YIELD_PCT AS SCS_DER_SEC_RESTATED_YIELD_PCT
    FROM SHARE_CLASS sc 
    INNER JOIN PORTFOLIO P ON (P.PORTFOLIO_SID=SC.PORTFOLIO_SID)
    INNER JOIN SHARE_CLASS_SNAPSHOT SCS ON 
    (SCS.SHARE_CLASS_SID=sc.SHARE_CLASS_SID)
    WHERE SCS.REPORTING_DT = '24-JUL-17' AND P.PORTFOLIO_ID = 638;

我运行此查询并获得以下输出:image

这里,我没有为同一个TAAC_SHARE_CLASS_ID获取单独的行,而是想合并相同TAAC_SHARE_CLASS_ID的输出。

例如,TAAC_SHARE_CLASS_ID = 000648的第一行应该包含所有4列的值:

SCS.DIST_UNMOD_30_DAY_YIELD_PCT, 
SCS.DER_DIST_12_MO_YIELD_PCT, 
SCS.DER_SEC_30_DAY_YIELD_PCT,
SCS.DER_SEC_RESTATED_YIELD_PCT.

因此第一行的值应为2.96,3.2972596,7541.085263433,7550。

我的输出的最后4行并不是真正需要的,因为我们现在已经将这些数据合并到前4行。

如何更改此查询以实现相同的目标?请帮忙。

1 个答案:

答案 0 :(得分:1)

我建议您按TAAC_SHARE_CLASS_ID列对结果进行分组,然后使用MAX()对其余列进行分组,如下所示:

SELECT  sc.TAAC_SHARE_CLASS_ID,
        max(SCS.SHARE_CLASS_SID) as SHARE_CLASS_SID,
        max(SCS.REPORTING_DT) as REPORTING_DT,
        max(SCS.SHARE_CLASS_SNAPSHOT_SID) as SHARE_CLASS_SNAPSHOT_SID, 
        max(SCS.DIST_UNMOD_30_DAY_YIELD_PCT) as DIST_UNMOD_30_DAY_YIELD_PCT, 
        max(SCS.DER_DIST_12_MO_YIELD_PCT) as DER_DIST_12_MO_YIELD_PCT, 
        max(SCS.DER_SEC_30_DAY_YIELD_PCT) AS SCS_DER_SEC_30_DAY_YIELD_PCT, 
        max(SCS.DER_SEC_RESTATED_YIELD_PCT) AS SCS_DER_SEC_RESTATED_YIELD_PCT
FROM SHARE_CLASS sc 
INNER JOIN PORTFOLIO P ON (P.PORTFOLIO_SID=SC.PORTFOLIO_SID)
INNER JOIN SHARE_CLASS_SNAPSHOT SCS ON (SCS.SHARE_CLASS_SID=sc.SHARE_CLASS_SID)
WHERE SCS.REPORTING_DT = '24-JUL-17' AND P.PORTFOLIO_ID = 638
GROUP BY sc.TAAC_SHARE_CLASS_ID;