Mysql 如何在SQL中按行分组?
这是我的测试表,我还有更多的列。我刚刚在这里展示了一些专栏Mysql 如何在SQL中按行分组?,mysql,sql,mysql-workbench,Mysql,Sql,Mysql Workbench,这是我的测试表,我还有更多的列。我刚刚在这里展示了一些专栏 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
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
有人能告诉我哪里出了问题吗 您似乎想要:
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`;
当需要对行而不是列求和时,可以使用SUM 要对字段求和,只需使用运算符 请尝试以下代码: 结果选择生物质+化石+棕色+煤炭 从测试
其中ID='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`
据我所知,我是这样做的
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
身份证件什么身份证?我看到索引了。此外,DateTime对于每一行都是唯一的,不是吗?整行要一个数字吗?不确定是否需要分组或求和?你能不能把它们加在一起——生物质量+化石+。。。?如果您确实需要对它们进行分组,您可能希望按日期分组,而不是按日期时间分组。在这种情况下,使用sum,但仍然要将它们加在一起suma+b+c…SQLServerMySQL。。请仅标记您实际使用的DBMS。另外,你真的有一个专栏叫[化石褐煤/褐煤,化石煤衍生气体]?您确实应该避免在对象名称中使用特殊字符,包括空格。@sgedes实际上DateTime是列名。@PraveenRB我的意思是类似于按cast[DateTime]分组作为日期-按时间戳分组可能不会将太多记录分组在一起。取决于你想要的结果。因此,对于示例数据,如果希望返回3个结果,则无需求和或分组,只需使用+。如果希望按日期而不是按时间得到1个结果,请将它们分组并求和……显示“选择”对该服务器版本无效。@PraveenRB听起来不像SQL servererror@YogeshSharma错误代码:1064。您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以了解在“[DateTime]、SumBiomal+[Fossil Brown coal/褐煤]+附近使用的正确语法第1行的[Fossil Coal-derived gas]我收到一个类似这样的错误。错误代码:1064。您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,以了解在“[DateTime],Sumbiors+[Fossil Brown Coal/褐煤]+附近使用的正确语法[Fossil Coal-derived gas]在第1行,由于您收到了MySQL反馈,我将假设正确的RDBMS是MySQL,而不是SQL Server。请尝试更新。