Sql 如何按分组并保留特定列

Sql 如何按分组并保留特定列,sql,group-by,Sql,Group By,拥有这张桌子: Number | Chapter | Main | Description | value -------+---------+---------+--------------+-------- 1 | 1 | false | description1 | 100 1 | 1 | false | description2 | 200 1 | 1 | true | main de

拥有这张桌子:

Number | Chapter |   Main  | Description  | value  
-------+---------+---------+--------------+--------  
1      |   1     |   false | description1 | 100  
1      |   1     |   false | description2 | 200  
1      |   1     |   true  | main desc.   | 0  
2      |   1     |   true  | main2        | 0
2      |   1     |   false | desc2        | 100

我需要按数字e章节和总和(值)进行分组,但当Main=true时,我需要描述(每个章节只有1个“Main”)

预期结果:

Number | Chapter | Description | value  
-------+---------+-------------+--------  
1      |   1     | main desc.  | 300  
2      |   1     | main2       | 100 

谢谢。

使用条件聚合:

select number, chapter,
  max(case when main = 'true' then description end) description,
  sum(value) value
from tablename
group by number, chapter
如果列的
main
数据类型为
boolean
,则更改为:

max(case when main then description end)

使用条件聚合:

select number, chapter,
  max(case when main = 'true' then description end) description,
  sum(value) value
from tablename
group by number, chapter
如果列的
main
数据类型为
boolean
,则更改为:

max(case when main then description end)

您可以使用
CASE
子句查找所需的描述:

select
  number,
  chapter,
  max(case when main = 'true' then description end) as description,
  sum(value) as value
from t
group by number, chapter

您可以使用
CASE
子句查找所需的描述:

select
  number,
  chapter,
  max(case when main = 'true' then description end) as description,
  sum(value) as value
from t
group by number, chapter

有数字1和数字2你如何得到200作为求和值?对不起,我的分心,显然是100有数字1和数字2你如何得到200作为求和值?对不起,我的分心,显然是100嘿。。。这就是我的答案!;-)嘿这就是我的答案!;-)嘿这就是我的答案!;-)只是还没有published@OtoShavadze嘿嘿。。。这就是我的答案!;-)只是还没有published@OtoShavadze英雄联盟