我是SQL的新手,请帮助我解决以下查询
SELECT DISTINCT
ROG.GROUPID,
CAPA1.PERC,
CAPA1.TPTID
FROM AGREGATEDPOLICY APO
INNER JOIN REINSURANCEOPERATION RO ON APO.AGREGATEDPOLICYID = RO.AGREGATEDPOLICYID
INNER JOIN REINSURANCEOPERATIONGROUPINFO ROG ON RO.OPERATIONID = ROG.OPERATIONID
INNER JOIN (SELECT RIC.GROUPID GID, RIP.PERCENTAGE PERC, RIP.THIRDPARTYID TPTID
FROM RI_REINSURANCECONTRACT RIC
INNER JOIN RI_CONTRACTCOMPONENT RICC ON RICC.MAINID = RIC.RCID
INNER JOIN RI_CCPARTICIPATION RICP ON RICP.CCID = RICC.CCID
INNER JOIN RI_PARTICIPATION RIP ON RIP.PARTICIPATIONID = RICP.PARTICIPATIONID
INNER JOIN RI_EXCESSLOSS RIE ON RIE.EXCESSLOSSID = RICC.CCID
INNER JOIN EXCESOPERDIDA EXP ON EXP.PK = RIE.EXCESSDCOID
WHERE RIC.REINSURANCECONTRACTTYPE = 0
AND RICC.TYPE = 'LossExcess') CAPA1 ON ROG.GROUPID = CAPA1.GID
现在,每个GROUPID可能有多个THIRDPARTYID。我想将25与每个THIRDPARTYID的PERCENTAGE相乘。
例如,如果输出为
GROUPID PERCENTAGE THIRDPARTYID
2824 0.4 824603
2824 0.4 824500
2824 0.5 824603
2824 0.2 824601
2824 0.5 824500
我想将输出显示为RESULT1 ..... n(如下所示,根据THIRDPARTYID动态更改n
GROUPID RESULT1 RESULT2 RESULT3 RESULT4 RESULT5
2824 10 10 12.5 5 12.5
在这里,我不是将行划分为列,我们应该将列中的值乘以某个数字,并在新列中以新列显示为值,如示例输出所示
预先感谢您的帮助。
答案 0 :(得分:1)
是的,您正在努力。您希望数据从五行变成一行五列,相乘并不重要。对于5列,您可以使用以下查询(或旧Oracle版本中的case when
等价):
select *
from (select groupid, percentage,
row_number() over (partition by groupid order by null) rn
from your_query)
pivot (sum(percentage * 25) as result for rn in (1, 2, 3, 4, 5))
对于动态列数,您需要解决建议重复问题的解决方案,SO上有很多类似的问题。
在case when
中,您还可以处理值超过5个的情况,添加一列的总和为6+或添加信息文本。