簡體   English   中英

SQL在一個查詢中按級別分組

[英]SQL Different Group By Levels within one query

我嘗試將一個維度的百分比除以另一個維度。 所以說我有

table1 =
country, product, sale
US, TV, 50
US, TV, 150
MEX, TV, 50
US, PC, 800

我希望按國家/地區的產品分組,並獲得:

Select... =
Country, Product, Country_Total, Product_Per_Country, Percentage
US, TV, 1000, 200, 20%
US, PC, 1000, 800, 80%
MEX, TV, 50, 50, 100%

我只想從table1中選擇一次,因為這是一個廣泛的選擇。 你能幫忙嗎?

彼得,許多問候

嘗試像下面使用窗口功能

 select country, product,sum(sum(sale)) over( partition by country) Country_Total,
sum(sum(sale))over( partition by country,product) Product_Per_Country,
 (sum(sum(sale))over( partition by country,product) /sum(sum(sale)) over( partition by country))*100 as Percentage
from cte group by country, product


COUNTRY     PRODUCT     COUNTRY_TOTAL   PRODUCT_PER_COUNTRY     PERCENTAGE
MEX         TV            50            50                      100
US          PC           1000           800                     80
US          TV           1000           200                     20

在線演示

使用窗口功能:

select country, product, sum(sale) as sales,
       sum(sale) / sum(sum(sale)) over (partition by country) as country_ratio
from table1 t1
group by country, product;

查詢就像

SELECT country, product, sum(sale) as sales,
sum(sale) / sum(sum(sale)) over (partition by country) as country_ratio
FROM table1
GROUP BY country, product;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM