如何在单个mysql表中添加总计的总和

时间:2012-09-25 05:36:14

标签: mysql database

我有以下MySQL表:

  • SITE_ID
  • 序列号
  • cost_per_month
  • cost_per_unit_A
  • cost_per_unit_B
  • opening_unit_A
  • closing_unit_A
  • opening_unit_B
  • closing_unit_B

    我执行以下MySQL查询:

    select 
    SITE_ID as 'Site', Serial Number,cost_per_month
    cost_per_unit_A, cost_per_unit_B,opening_unit_A, closing_unit_A, opening_unit_B, closing_unit_B
    format(cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,2) as 'Total Vat Ex',
    format((cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,*0.14,2)) as 'Vat',
    format((cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,*1.14,2)) as 'Total Vat inclusive'
    where SITE_ID ='Site Name'
    

    我想更改此查询,以便总计最后一次添加查询的总和。

    我会使用group by语句吗?

  • 1 个答案:

    答案 0 :(得分:0)

    select 
    SITE_ID as 'Site', 
    Serial Number,
    cost_per_month
    cost_per_unit_A, 
    cost_per_unit_B,
    opening_unit_A,
    closing_unit_A, 
    opening_unit_B, 
    closing_unit_B,
    SUM(format(cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,2)) as 'Total Vat Ex',
    SUM(format((cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,*0.14,2))) as 'Vat',
    SUM(format((cost_per_month+(closing_unit_A-opening_unit_A)*cost_per_unit_A+(closing_unit_B-opening_unit_B)*cost_per_unit_A,*1.14,2))) as 'Total Vat inclusive'
    From reading
    where SITE_ID ='Site Name'
    Group By 
    SITE_ID, 
    Serial Number,
    cost_per_month
    cost_per_unit_A, 
    cost_per_unit_B,
    opening_unit_A,
    closing_unit_A, 
    opening_unit_B, 
    closing_unit_B