简体   繁体   English

sql查询以基于条件求和数据

[英]sql query to sum data based on criteria

I have my table data sums as follows 我的表数据总和如下

---------------------
Building   | Area m2
---------------------
|Dante 12  |   10
|Dante 10  |    5
|Dante 9   |    2
|Crandley  |   20
|Bence     |   30

I want to sum Building Area but buildings like '%dante%' I want to combine into sum "Dante" like below: 我想对“建筑面积”求和,但是像“%dante%”这样的建筑物要合并成“ Dante”之和,如下所示:

-------------------
Building | Area m2
-------------------
Dante    |  17
Crandley |  20
Bence    |  30

Group by with case will do the trick for sample data given, like of this type can use index as well 按大小写分组将为给定的示例数据提供诀窍, like此类也可以使用索引

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

if there are numbers for other columns,you can strip out the numbers first and do the rest of stuff like below 如果其他栏位有数字,您可以先去除数字,然后进行其余的操作,如下所示

;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

References: 参考文献:
Remove numbers found in string column 删除在字符串列中找到的数字

Works only if numeric value is to be removed 仅在要删除数值时有效

Numeric value is to be replaced (Nested replace function can go upto 32 level deep) and group by column. 要替换的数值(嵌套替换功能最多可扩展到32级)并按列分组。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM