如何将获取的此查询值乘以SQL中另一个查询的输出值?

时间:2016-11-16 10:50:11

标签: sql sql-server database rdbms

我不是很喜欢SQL,而是在Microsoft SQL Server上进行此查询

SELECT
    tr.PolizzaID AS NumeroPolizza,
    pfr.FondoID AS CodiceFondo,
    '2016-09-30' AS dataRiferimentoPrezzo,
    SUM(isnull(pre.impPre,0)+isnull(riv.impRiv,0)) AS quote,
    SUM(isnull(pre.impPre,0)+isnull(riv.impRiv,0)) AS Controvalore
FROM
    TR_PrestazioneTotale tr WITH(nolock)

    ............................................................
    ............................................................
    DO SOME JOIN OPERATIONS
    ............................................................
    ............................................................

WHERE
    tr.PolizzaID = 1234567890
GROUP BY
    tr.PolizzaID,
    pfr.FondoID
HAVING 
    SUM(ISNULL(pre.impPre, 0) + ISNULL(riv.impRiv, 0)) <> 0

此查询始终返回单个值

正如您所看到的,上一个查询中选择的列之一就是这一列:

SUM(ISNULL(pre.impPre, 0) + ISNULL(riv.impRiv, 0)) AS Controvalore

这是一个数值(类似 550058.8400 )。

我的问题是我必须乘以这个

SUM(ISNULL(pre.impPre, 0) + ISNULL(riv.impRiv, 0))

此其他查询的输出值:

select Aliquota 
from TirAliquotaRamoI 
where DataElaborazione = '2016-09-30 00:00:00'

此查询也始终返回单值

所以基本上,第一个查询的 Controvalore 输出字段必须是 SUM(isnull(pre.impPre,0)+ isnull(riv.impRiv,0))的结果乘以第二个查询的 Aliquota 输出值。

我该怎么做?

由于

1 个答案:

答案 0 :(得分:1)

由于两者都返回单个结果,因此您可能......可能会在SELECT子句中使用子查询。我猜这个aliquota名称可能会对你的情况有所帮助,但这实际上取决于下面的数据。无论如何,这是一个很好的起点。

SELECT
    tr.PolizzaID                                   AS NumeroPolizza,
    pfr.FondoID                                    AS CodiceFondo,
    '2016-09-30'                                   AS dataRiferimentoPrezzo,
    SUM(isnull(pre.impPre,0)+isnull(riv.impRiv,0)) AS quote,
    SUM(isnull(pre.impPre,0)+isnull(riv.impRiv,0)) * (select Aliquota from TirAliquotaRamoI where DataElaborazione = '2016-09-30 00:00:00') AS Controvalore
FROM
    TR_PrestazioneTotale tr WITH(nolock)

    ............................................................
    ............................................................
    DO SOME JOIN OPERATIONS
    ............................................................
    ............................................................

WHERE
    tr.PolizzaID = 1234567890
GROUP BY
tr.PolizzaID ,
pfr.FondoID
HAVING SUM(isnull(pre.impPre,0)+isnull(riv.impRiv,0)) <>0