我有以下数据:
Date ID Type Cost
May 01 a A 1
May 01 b A 2
May 01 c B 3
May 01 d B 4
May 02 e A 5
May 02 f A 6
May 02 g B 7
May 02 h B 8
我想要一个显示
的查询Date Type CostPercentage
May 01 A (1+2) / (1+2+3+4)
May 01 B (3+4) / (1+2+3+4)
May 02 A (5+6) / (5+6+7+8)
May 02 B (7+8) / (5+6+7+8)
我目前拥有的是
select Date, Type, sum(cost)
from mytable
group by Date, Type
我真的想要显示百分比,但这将涉及分配另一个本身就是聚合的数字。
我怎么想这样做?
编辑以反映我的真实问题。我之前简化了它。
答案 0 :(得分:1)
您可以使用子查询:
select dt.Date
, dt.Type
, SUM(dt.Cost) as DayTypeTotal
, (select SUM(Cost) from @t d where d.Date = dt.Date) as DayTotal
, 100.0 * SUM(dt.Cost) /
(select SUM(Cost) from @t d where d.Date = dt.Date) as Percentage
from @t dt
group by
dt.Date
, dt.Type
答案 1 :(得分:1)
此查询应该按照需要工作,“o”是外部表,“i”是内部表:
select o.date,
o.type,
sum(o.cost) / (select sum(i.cost) from mytable as i where i.date=o.date) * 100.0
from mytable as o
group by
o.date,o.type
对于此示例数据:
Day1, A, 1
Day2, A, 2
Day1, B, 3
Day2, B, 4
结果是:
答案 2 :(得分:0)
select
mytable.date, mytable.type, sum(mytable.cost)/day.total_cost
from mytable
inner join
(select date, sum(cost) as total_cost from mytable group by date) as day
on day.date=mytable.date
group by mytable.date, mytable.type