sql查询根据条件求和数据

时间:2016-08-16 15:53:48

标签: sql sum

我的表数据总和如下

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

我想总结一下建筑区域,但是像#dan;%dante%'我想结合总和" Dante"如下所示:

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

2 个答案:

答案 0 :(得分:2)

group by with case将为所提供的样本数据提供技巧,此类型的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

如果其他列有数字,您可以先删除数字,然后执行下面的其他操作

;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

答案 1 :(得分:0)

仅在要移除数值时才有效

要替换数字值(嵌套替换函数最多可以达到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