[英]SQL - aggregation with groupby and partitioning
I have a table that looks like this called sales
我有一张看起来像这样的桌子叫sales
brand | model | sales
--------+----------+------
brand1 | model11 | 100
brand1 | model11 | 300
brand2 | model21 | 100
brand2 | model22 | 400
brand3 | model31 | 100
I was using the following SQL query 我正在使用以下SQL查询
SELECT
brand, SUM(sales)/SUM(sales) OVER () as sales_share
FROM sales
GROUP BY brand
So as to get the sales_share
for each brand as below 以便如下获得每个品牌的sales_share
brand | sales_share
--------+--------------
brand1 | 0.4
brand2 | 0.5
brand3 | 0.1
However, I was getting error Attribute SALES.sales must be GROUPed or used in an aggregate function
- any pointers ? 但是,我遇到错误Attribute SALES.sales must be GROUPed or used in an aggregate function
-是否有任何指针?
The following works 以下作品
SELECT
brand, SUM(sales)/SUM(SUM(sales)) OVER () as sales_share
FROM sales
GROUP BY brand
What was missing in the original attempt was the aggregation function - exactly like the error message said :) 最初尝试中缺少的是聚合功能-就像错误消息中所说的一样:)
If you are using sql you should group by each attribute you select. 如果使用的是sql,则应按选择的每个属性分组。 So your query would be something like : 因此,您的查询将类似于:
SELECT
brand, SUM(sales)/SUM(sales) OVER () as sales_share
FROM sales
GROUP BY brand, sales
You can use, 您可以使用,
select
brand, SUM(sales)as brand_sales
into tmp
from sales
group by brand
select brand ,
total_sales /(select SUM(b.sales) from sales b) as total_sales
from tmp
drop table tmp
Try this : 尝试这个 :
select brand , sales_share/sum(sales_share) over () sales_share from (
SELECT
brand, SUM(sales) as sales_share
FROM sales
GROUP BY brand
) a
You don't really need a window function for this: 您实际上并不需要窗口函数:
SELECT brand,
sum(sales) / (select sum(sales) from sales) as sales_share
FROM sales
GROUP BY brand;
Depending on the data type of sales
you might need a cast to a decimal, otherwise Postgres will use integer division 根据sales
的数据类型,您可能需要将其强制转换为小数,否则Postgres将使用整数除法
SQLFiddle: http://sqlfiddle.com/#!15/548ad/1 SQLFiddle: http ://sqlfiddle.com/#!15/548ad/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.