我有一个名为sales
brand | model | sales
--------+----------+------
brand1 | model11 | 100
brand1 | model11 | 300
brand2 | model21 | 100
brand2 | model22 | 400
brand3 | model31 | 100
我正在使用以下SQL查询
SELECT
brand, SUM(sales)/SUM(sales) OVER () as sales_share
FROM sales
GROUP BY brand
为每个品牌获取sales_share
,如下所示
brand | sales_share
--------+--------------
brand1 | 0.4
brand2 | 0.5
brand3 | 0.1
然而,我收到错误Attribute SALES.sales must be GROUPed or used in an aggregate function
- 任何指针?
答案 0 :(得分:1)
以下作品
SELECT
brand, SUM(sales)/SUM(SUM(sales)) OVER () as sales_share
FROM sales
GROUP BY brand
原始尝试中缺少的是聚合函数 - 与错误消息所说的完全相同:)
答案 1 :(得分:0)
如果您使用的是sql,则应按您选择的每个属性进行分组。所以你的查询将是这样的:
SELECT
brand, SUM(sales)/SUM(sales) OVER () as sales_share
FROM sales
GROUP BY brand, sales
答案 2 :(得分:0)
你可以使用,
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
答案 3 :(得分:0)
试试这个:
select brand , sales_share/sum(sales_share) over () sales_share from (
SELECT
brand, SUM(sales) as sales_share
FROM sales
GROUP BY brand
) a
答案 4 :(得分:0)
你真的不需要窗口功能:
SELECT brand,
sum(sales) / (select sum(sales) from sales) as sales_share
FROM sales
GROUP BY brand;
根据sales
的数据类型,您可能需要转换为小数,否则Postgres将使用整数除法
SQLFiddle:http://sqlfiddle.com/#!15/548ad/1