如何使两个查询的值之间的比率?

时间:2017-07-03 14:37:07

标签: sql sql-server sql-server-2016

我有这两个问题

 SELECT
    COUNT(DISTINCT s.KliRC) Celkem
    ,r.Region
FROM dbo.Smlouvy s
        JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
        JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu   
GROUP BY
    r.Region

-- +

SELECT
    COUNT(DISTINCT s.KliRC) Solus
    ,r.Region
FROM dbo.SolusDetaily sd
    JOIN dbo.Smlouvy s      ON sd.CisloZadosti    = s.CisloSmlouvy    
        JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
        JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu
GROUP BY
    r.Region

我想在(计数)字段中建立它们之间的比率。 我用cte尝试了UNION ALL,但是没有预期的结果。

3 个答案:

答案 0 :(得分:1)

我认为你可以INNER JOIN两个子查询。
使用NULLIF(c.Celkem,0)来避免被零除错误。

SELECT s.Region, (s.Solus * 1.0)/NULLIF(c.Celkem,0) as Ratio
FROM
(
    SELECT
            COUNT(DISTINCT s.KliRC) Solus
            ,r.Region
    FROM dbo.SolusDetaily sd
        JOIN dbo.Smlouvy s      ON sd.CisloZadosti    = s.CisloSmlouvy    
            JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
            JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu
    GROUP BY
        r.Region
) s
INNER JOIN 
(
    SELECT
            COUNT(DISTINCT s.KliRC) Celkem
            ,r.Region
    FROM dbo.Smlouvy s
            JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
            JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu   
    GROUP BY
        r.Region
) c on  s.Region = c.Region

答案 1 :(得分:0)

尝试这样的事情。

select Region,(Celkem * 1.0) /sum(Celkem)over() as Ratio
(
selcet Region, COUNT(DISTINCT s.KliRC) Celkem
from ..
Union All
selcet Region, COUNT(DISTINCT s.KliRC) Solus
from ..
) A

答案 2 :(得分:0)

您可以使用公用表格表达式:

    with t1 as
    (
    SELECT
        COUNT(DISTINCT s.KliRC) Celkem
        ,r.Region Region
    FROM dbo.Smlouvy s
            JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
            JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu   
    GROUP BY
        r.Region
    ),
    with t2 as
    (

    SELECT
        COUNT(DISTINCT s.KliRC) Solus
        ,r.Region Region
    FROM dbo.SolusDetaily sd
        JOIN dbo.Smlouvy s      ON sd.CisloZadosti    = s.CisloSmlouvy    
            JOIN CS_OZ oz       ON oz.KodOZ = s.KodOZ
            JOIN CS_Regiony r   ON r.KodRegionu = oz.KodRegionu
    GROUP BY
        r.Region
    ) 
    -- get ratio
    select t1.region , t1.Celkem /t2.Solus as ratio
    from t1
    join t2 on t1. Region = t2.Region