如何在sql中按行分组?

o4hqfura  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(401)

这是我的测试表(还有更多的列)。我刚刚展示了这里的一些专栏。

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)
有人能告诉我哪里出了问题吗?

kadbb459

kadbb4591#

据我所知我是这么做的,

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
7uhlpewt

7uhlpewt2#

我想这就是你想要达到的目标:

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`
dojqjjoe

dojqjjoe3#

你似乎想要:

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`;
dced5bon

dced5bon4#

当需要对行(而不是列)求和时,可以使用sum()。
要对字段求和,只需使用运算符。
请尝试以下代码: SELECT ( Biomass + Fossil + Brown + Coal ) AS result FROM test WHERE ID = '0';

相关问题