首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据条件对数据求和的sql查询

根据条件对数据求和的sql查询
EN

Stack Overflow用户
提问于 2016-08-16 23:53:48
回答 2查看 274关注 0票数 1

我的表数据和如下所示

代码语言:javascript
复制
---------------------
Building   | Area m2
---------------------
|Dante 12  |   10
|Dante 10  |    5
|Dante 9   |    2
|Crandley  |   20
|Bence     |   30

我想要对建筑面积求和,但像'%dante%‘这样的建筑物我想合并成如下所示的和"Dante“:

代码语言:javascript
复制
-------------------
Building | Area m2
-------------------
Dante    |  17
Crandley |  20
Bence    |  30
EN

回答 2

Stack Overflow用户

发布于 2016-08-16 23:56:14

Group by with case将对给定的样本数据执行此操作,此类型的like也可以使用索引

代码语言:javascript
复制
Select 
case when building like 'dante%' then 'Dante' else building end,
sum([area m2])
from
table
group by 
case when building like 'dante%' then 'Dante' else building end

如果有其他列的数字,可以先去掉这些数字,然后再做下面的事情

代码语言:javascript
复制
;with cte
as
(select REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (building, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '') as bulding,aream2
 from #temp
)
select building,sum(aream2)
from
cte 
group by 
building

参考:

Remove numbers found in string column

票数 2
EN

Stack Overflow用户

发布于 2016-08-17 00:14:29

仅当要删除数值时,才起作用

数值将被替换(嵌套的替换函数最深可达32层),并按列分组。

代码语言:javascript
复制
SELECT x.Building, SUM(x.AreaM2) AS [Area m2]
FROM (
    SELECT 
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE (Building, '0', '')
        ,'1', '')
        ,'2', '')
        ,'3', '')
        ,'4', '')
        ,'5', '')
        ,'6', '')
        ,'7', '')
        ,'8', '')
        ,'9', '') [Building], AreaM2 FROM Buildings) AS x
GROUP BY x.Building
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38979378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档