我有这样的查询结果,选择类型,Jan,FEB From TableName:
+-----------+------+------+
| Type | JAN | FEB |
+-----------+------+------+
| MATIC | 137 | 128 |
| MOPED | 41 | 23 |
| MOPED PRM | 8 | 9 |
| SPORT | 55 | 62 |
+-----------+------+------+
4 rows in set (1.23 sec)
我想将列jan和列feb加起来,就像这样
+-----------+------+------+------+
| Type | JAN | FEB | TOT |
+-----------+------+------+------+
| MATIC | 137 | 128 | 165 |
| MOPED | 41 | 23 | 64 |
| MOPED PRM | 8 | 9 | 17 |
| SPORT | 55 | 62 | 117 |
+-----------+------+------+------+
4 rows in set (1.23 sec)
是否有诸如
之类的命令select type, jan, feb, sum (jan) + sum (feb) As TOT
From Table Name
这是我的语法
Select SubTbl2.jenis,
sum(If(Month = 1 and Year = 2013 ,Result,0)) as 'JAN',
sum(If(Month = 2 and Year = 2013,Result,0)) as 'FEB'
From (
select SubTbl1.jenis,month(SubTbl1.TglAmb) as Month,
year(SubTbl1.tglAmb) as Year,
count(SubTbl1.jenis) as Result
From (
select jual_leasing.TglAmb,jual_leasing.NoMsn,typemotor.jenis
,lokasi.lokasi3s
from jual_leasing
left join typeconvert
on jual_leasing.typeK = typeconvert.typesystem
left join typemotor
on typeconvert.typeconv = typemotor.type
left join lokasi
on jual_leasing.kodelok = lokasi.kodelokasi
where
lokasi.lokasi3S = 'YMS PURWODADI 3S'
group by jual_leasing.NoMsn)
as SubTbl1
group by SubTbl1.jenis,Month,Year )
as SubTbl2 group by SubTbl2.jenis;
结果在Top上,我尝试在第4行添加脚本 JAN + FEB作为TOT
但是有警告: ERROR 1054(42S22):'字段列表'中未知列'JAN'
Tq For advanced
答案 0 :(得分:4)
要获得游览所需的输出,只需执行以下操作:
select type, jan, feb, jan + feb As TOT
from TableName
您不需要SUM
,它旨在添加不同行的值。
编辑对于您的实际查询,是的,您可以添加两个总和。此外,以下内容适合您:
sum(If((Month = 1 or Month = 2) and Year = 2013 ,Result,0)) as 'TOT',
答案 1 :(得分:1)
arithmetic functions上的MySQL文档表明+
确实是加法运算符。
因此,您的查询将是:
select type, jan, feb, jan + feb from table
Sum适用于列而非行;如果你想将两列的总和加在一起,你可以使用它。
P.S。 137 + 128 = 265
答案 2 :(得分:1)
我认为你会发现这个问题正在下降,因为它不是真正的编程 - 这更像是一般的SQL语法问题。话虽如此,我认为你应该能够总结你的价值观:
select type, jan, feb, jan + feb As TOT From Table Name
答案 3 :(得分:0)
只需使用以下命令更改查询的开头:
Select SubTbl2.jenis,
sum(If(Month = 1 and Year = 2013 ,Result,0)) as 'JAN',
sum(If(Month = 2 and Year = 2013,Result,0)) as 'FEB',
sum(If(Month = 1 and Year = 2013 ,Result,0)) +
sum(If(Month = 2 and Year = 2013,Result,0)) as 'TOT'
From (
或者
Select SubTbl2.jenis,
sum(If(Month = 1 and Year = 2013 ,Result,0)) as 'JAN',
sum(If(Month = 2 and Year = 2013,Result,0)) as 'FEB',
sum(If((Month = 1 or Month = 2) and Year = 2013,Result,0)) as 'TOT'
From (