基于Region和Cluster查询SQL的计算

时间:2017-12-05 07:26:12

标签: sql postgresql

我有这样的表:

int main()
{
    unsigned u = 10; int i = -8;
    std::cout << u + i << std::endl; 
    return 0;
}

获取基于群集的值和总和的值,变为值25900和第8卷。获取基于区域的值和总和的总和,变为值(7500,9000,9400)和体积(2,1,5)。然后基于区域的值和体积除以基于聚类的值和体积。数据应该是这样的:

Cluster | Region | Value | Volume
---------------------------------
 West   |   AA   |  7500 |   2
 West   |   AB   |  9000 |   1
 West   |   AC   |  2200 |   2
 West   |   AC   |  7200 |   3

SQL小提琴:http://sqlfiddle.com/#!15/5a908/27

3 个答案:

答案 0 :(得分:1)

尝试:

SELECT
A."Region", round((A."Region_VALUE"*100/B."CLUSTER_VALUE"),2) AS GROWTH_VALUE, 
round((A."Region_VOLUME"*100/B."CLUSTER_VOLUME"),2) AS GROWTH_VOLUME
FROM
  ( SELECT "Region", SUM("Value") AS "Region_VALUE", SUM("Volume") AS "Region_VOLUME"
  FROM cals
  GROUP BY "Region" 
  ) A,
  ( SELECT SUM("Value") AS "CLUSTER_VALUE", SUM("Volume") AS "CLUSTER_VOLUME"
  FROM cals
  ) B;

答案 1 :(得分:0)

我们可以尝试进行两个单独的聚合,一个在集群级别,一个在区域级别。然后加入他们并获取您想要查看的商数。

WITH cluster AS (
    SELECT "Cluster", SUM("Value") AS c_value, SUM("Volume") AS c_volume
    FROM cals
    GROUP BY "Cluster"
),
region AS (
    SELECT "Cluster", "Region",
        SUM("Value") AS r_value, SUM("Volume") AS r_volume
    FROM cals
    GROUP BY "Cluster", "Region"
)

SELECT
    r."Region",
    r."Cluster",
    ROUND(100.0*r.r_value / c.c_value, 1) AS growth_value,
    ROUND(100.0*r.r_volume / c.c_volume, 1) AS growth_volume
FROM region r
INNER JOIN cluster c
    ON r."Cluster" = c."Cluster"
ORDER BY
    r."Region";

Demo

答案 2 :(得分:0)

基本上,如果您需要1个直接查询,请参阅下文。我不确定逗号29,0后的数据是什么。您可以在此之后修改为逗号后的内容

    select cals."Region",
ROUND(100.0 * r."Value" / c."Value",1) as "Growth Value",
ROUND(100.0 * r."Volume" / c."Volume",1) as "Growth Volume"  
    from cals 
    inner join
    (select "Cluster",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals 
    group by "Cluster") as c 
    on c."Cluster" = cals."Cluster"
    inner join
    (select "Region",
    SUM("Value") as "Value",
    SUM("Volume") as "Volume"
    from cals 
    group by "Region") as r
    on r."Region" = cals."Region"
    group by cals."Region",r."Value",c."Value",c."Volume",r."Volume"

结果

enter image description here