如何使用不同的聚合构造SQL查询

时间:2011-03-09 11:04:24

标签: mysql sql tsql

我有以下数据:

 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

我真的想要显示百分比,但这将涉及分配另一个本身就是聚合的数字。

我怎么想这样做?

编辑以反映我的真实问题。我之前简化了它。

3 个答案:

答案 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

链接到working example @odata

答案 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

结果是:

  • A类费用占25% 第1天总费用(1/1 + 3)。
  • B型 成本占第一天的75% 总费用(3/1 + 3)。
  • A类费用 占第二天总数的约33% 费用(2/2 + 4)。
  • B类成本弥补 占总成本的约66%(4 / 2 + 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