I have a table that looks like this called 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
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
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 ?
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. 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
SQLFiddle: http://sqlfiddle.com/#!15/548ad/1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.