-1

我有这样的查询结果,从 TableName 中选择 Type,Jan,FEB:

    +-----------+------+------+
    | 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;

结果在顶部,我尝试在第 4 行添加脚本,以 JAN + FEB 作为 TOT

但仍然有警告:ERROR 1054 (42S22): Unknown column 'JAN' in 'field list'

Tq 高级

4

4 回答 4

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',
于 2013-09-01T17:59:08.933 回答
1

MySQL 关于算术函数的文档表明这+确实是加法运算符。

因此,您的查询将是:

select type, jan, feb, jan + feb from table

Sum 适用于列而不是行;如果您希望将两列的总和相加,您可以使用它。

PS 137 + 128 = 265

于 2013-09-01T18:00:21.227 回答
1

我想你会发现这个问题被否决了,因为它与编程无关——这更像是一个一般的 SQL 语法问题。话虽这么说,我认为你应该能够总结你的价值观:

select type, jan, feb, jan + feb As TOT From Table Name
于 2013-09-01T18:01:33.787 回答
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 (
于 2013-09-01T18:28:26.797 回答