在SUM函数中使用通配符

时间:2016-02-23 12:28:21

标签: sql sql-server tsql

我有一个查询,其中我想根据另一列中的值(使用通配符)对一列中的区域求和。 在总结区域之前,我的数据看起来像这样:

ID              Classification                 Area
--------------------------------------------------------
1                  1-2-0-1                      30
1                  1-2-1-1                      55
1                  1-2-1-1                      15
1                  1-4-0-1                      60
2                  1-2-0-1                      50                      
2                  1-2-0-1                      100
2                  1-4-1-0                      45
2                  1-4-1-1                      35

现在我想总结按分类和ID划分的区域,我完成了以下操作:

SELECT
  ID,
  Classification,
  SUM(Area) over (partition by Classification order by ID)

FROM MyTable

WHERE   (Classification LIKE '1-2-%' OR     
        Classification LIKE '1-4-%')

返回

ID              Classification                 Area
--------------------------------------------------------
1                  1-2-0-1                      30
1                  1-2-1-1                      70
1                  1-4-0-1                      60
2                  1-2-0-1                      150                      
2                  1-4-1-0                      45
2                  1-4-1-1                      35

在搜索特定(独特)字符时,这非常有效。但是,我希望我的函数能够将所有只在前三个字符中相似的行相加,得到类似

的内容
ID              Classification                 Area
--------------------------------------------------------
1                  1-2-%                        100
1                  1-4-%                         60
2                  1-2-%                        150                      
2                  1-4-%                         80

有谁知道如何做到这一点?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

使用left()

SELECT ID, Classification,
       SUM(Area) over (partition by LEFT(Classification, 3) order by ID)
FROM MyTable
WHERE Classification LIKE '1-2-%' OR     
      Classification LIKE '1-4-%';

编辑:

乍一看,您似乎希望聚合数据,然后累计求和。为此:

SELECT ID, LEFT(Classification, 3),
       SUM(SUM(Area)) over (partition by LEFT(Classification, 3) order by ID)
FROM MyTable
WHERE Classification LIKE '1-2-%' OR     
      Classification LIKE '1-4-%'
GROUP BY ID, LEFT(Classification, 3);

答案 1 :(得分:0)

打败我@Gordon!

SELECT * INTO #Test FROM (VALUES
  (1, '1-2-0-1', 30),
  (1, '1-2-1-1', 55),
  (1, '1-2-1-1', 15),
  (1, '1-4-0-1', 60),
  (2, '1-2-0-1', 50),                    
  (2, '1-2-0-1', 100),
  (2, '1-4-1-0', 45),
  (2, '1-4-1-1', 35)) A (Id, Classification,Area)


SELECT DISTINCT Id, LEFT(Classification,3)+'-%' Classification, SUM(Area) OVER (PARTITION BY Id,LEFT(Classification,3)) Sum FROM #Test

Id          Classification Sum
----------- -------------- -----------
1           1-2-%          100
1           1-4-%          60
2           1-2-%          150
2           1-4-%          80