MySql所有行总和为一列

时间:2017-02-22 09:00:17

标签: php mysql

我尝试创建一个查询来选择表中所有行的总和为一列名称newtotal

这是我的查询

SELECT * 
FROM   tbl_activities
       ,(SELECT SUM(db_newtotal) as total FROM tbl_activities)  {$sql}

{$ sql}是column_name =从搜索表单输入的地方

但我有这个错误:

  

每个派生表都必须有自己的别名

我试着这样做:

SELECT * 
FROM tbl_activities
     ,(SELECT SUM(db_newtotal) as total FROM tbl_activities) as Table {$sql} 

但我有这个错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   附近的表格db_projectname =' Barbara Bui''在第1行

我打印查询,这是输出

SELECT * 
FROM tbl_activities
     ,(SELECT SUM(db_newtotal) as total FROM tbl_activities) as Table 
where db_projectname='Barbara Bui'

我想要的输出应该是这样的:ll记录项目名称=' Barbara Bui'总和新总计

projectname   location    Cost
Barbara Bui   verdun      100
Barbara Bui   kaslik      200 
Barbara Bui   achrafieh   500
Total                     800

查询

 SELECT * FROM tbl_activities
        union all
        select db_id,db_category,db_subcategory,db_taskname,db_predecessors,db_unit,db_qty,db_wo,db_duration,db_startdate,db_enddate,db_asd,db_add,db_transferredto,db_prb,db_anotes,db_aduration,db_projectname,db_A,db_AA,db_AAA,db_cost,db_status,db_room,db_floor,db_date,sum(db_newtotal) as total from tbl_activities
       {$sql}

2 个答案:

答案 0 :(得分:2)

错误是因为table是保留关键字。

你想这样使用UNION ALL

select projectname, location, cost
from tbl_activities {$sql}

union all

select 'Total', null, sum(cost)
from tbl_activities {$sql};

使用该参数应用where子句,它变为:

select projectname,
    location,
    cost
from tbl_activities {$sql}

union all

select 'Total',
    null,
    sum(cost)
from tbl_activities {$sql}

如果你在UNION ALL的第一部分有更多的列,那么请确保在第二个选择中包含所有那些空值。

select db_id, db_category, db_subcategory, db_taskname, db_predecessors, db_unit, db_qty, db_wo, db_duration, db_startdate, db_enddate, db_asd, db_add, db_transferredto, db_prb, db_anotes, db_aduration, db_projectname, db_A, db_AA, db_AAA, db_cost, db_status, db_room, db_floor, db_date, db_newtotal
from tbl_activities {$sql}

union all

select null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, sum(db_newtotal)
from tbl_activities {$sql}

答案 1 :(得分:0)

表是大多数RDMS中的保留字,因此您不能将其用作别名,请尝试更改为

SELECT * FROM tbl_activities,(SELECT SUM(db_newtotal) as total FROM tbl_activities) as myTable {$sql}

并查看是否有效