2016-02-23 61 views
2

我有一個查詢,我想根據另一列中的值(使用通配符)將一列中的區域求和。 我的數據是這個樣子的面積相加前:在SUM函數中使用通配符

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 

有沒有人有一個想法如何做到這一點?

任何幫助將不勝感激。

回答

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); 
0

打我吧@戈登!

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