这是我的测试表(仍然有更多列)。我刚刚在这里显示了一些专栏。
index DateTime Biomass Fossil Brown coal/Lignite Fossil Coal-derived gas
0 2/3/2018 23:00 4815 17359 192
1 2/3/2018 23:15 4811 17364 192
2 2/3/2018 23:30 4801 17356 192
在这里,我想对每行总计(生物质,化石棕煤/褐煤,化石煤衍生的气体)。
我已经尝试过了。
select SUM([Biomass], [Fossil Brown coal/Lignite,Fossil Coal-derived gas])
From test
Where ID = '0'
Group by DateTime
但未获得预期的结果。 预期结果将为(4815 + 17359 + 192 = 22366)
有人可以建议我哪里出了问题吗?
答案 0 :(得分:1)
您似乎想要:
SELECT [DateTime], SUM(Biomass + [Fossil Brown coal/Lignite] + [Fossil Coal-derived gas])
FROM test t
WHERE ID = '0'
GROUP BY [DateTime];
编辑:您的错误提示为MySQL
,因此您的查询为
SELECT `DateTime`, SUM(`Biomass` + `Fossil Brown coal/Lignite` + `Fossil Coal-derived gas`)
FROM `test` t
WHERE `ID` = '0'
GROUP BY `DateTime`;
答案 1 :(得分:0)
当需要累加行而不是列时,可以使用SUM()。
要对字段求和,只需使用运算符即可。
尝试以下代码:
SELECT ( Biomass + Fossil + Brown + Coal ) AS result
FROM test
WHERE ID = '0';
答案 2 :(得分:0)
我认为这是您要实现的目标:
SELECT [DateTime],
SUM(Biomass +
[Fossil Brown coal/Lignite] +
[Fossil Coal-derived gas]) AS MySum
FROM test
WHERE Index = 0
GROUP BY [DateTime]
仅供参考-您可能需要考虑将某些列重命名为不会过度使用特殊字符的东西。
编辑(对于MySQL):
SELECT `DateTime`,
SUM(Biomass +
`Fossil Brown coal/Lignite` +
`Fossil Coal-derived gas`) AS MySum
FROM test
WHERE Index = 0
GROUP BY `DateTime`
答案 3 :(得分:0)
据我所知,
create table #temp([index] int identity(0,1),DateTime datetime,Biomass int,Fossil int,Brown int,[coal/Lignite] int
,[Fossil_Coal-derived] int,gas int)
select * from #temp
insert into #temp(DateTime,Biomass,Fossil,Brown,[coal/Lignite],[Fossil_Coal-derived],gas)
values('2/3/2018 23:30',4801,17356,589,1246,5200,192)
select SUM([Biomass]+[Fossil]+[Brown]+[coal/Lignite]+[Fossil_Coal-derived]+[gas]) total
From #temp
Where [index] = '0'
Group by DateTime