2016-11-30 24 views
0

的时候我就喜欢做这样的事情使用子查询,而不使用子查询有总:选择总不分割

select 
    category, 
    date, 
    sum(qty)/(select sum(qty) from table where t.date= table.date) as share_of_total 
    from table t 
    group by category,date; 

表看起来是这样的:

category date qty 
1 2016-11-01 3 
1 2016-12-01 4 
2 2016-12-01 6 
2 2016-11-01 7 

预期结果如下:

category date share_of_total 
1 2016-11-01 30% 
2 2016-11-01 70% 
1 2016-12-01 40% 
2 2016-12-01 60% 
+0

请给出表格定义和数据,以帮助您完成 –

+0

!希望现在更清楚。 –

回答

1

已更新

这就是答案:

b=# create table "table" (category int,"date" date,qty int); 
CREATE TABLE 
b=# insert into "table" values (1,'2016-11-01',3), (1,'2016-12-01',4), (2,'2016-12-01',6), (2,'2016-11-01',7); 
INSERT 0 4 
b=# select 
    category 
, "date" 
, concat((qty*100)/sum(qty) over (partition by "date") ,'%') share_of_total from "table" 
order by "date", category 
; 
category | date | share_of_total 
----------+------------+---------------- 
     1 | 2016-11-01 | 30% 
     2 | 2016-11-01 | 70% 
     1 | 2016-12-01 | 40% 
     2 | 2016-12-01 | 60% 
(4 rows) 

而例子中,你应该如何问你的问题。将模式创建纳入问题可节省打字时间,以重现您拥有的内容。人们可能不想花时间来帮助你,只是因为你没有花你的时间来提供一个沙箱。

+0

这不提供问题的答案。要批评或要求作者澄清,请在其帖子下方留言。 - [来自评论](/评论/低质量帖/ 14454717) –

+0

@PedroWerneck我修改作者查询没有子查询,并给出相同的结果。正如他在他的问题中明确表示的那样如果你认为我应该删除我的答案,我会的。你做? –