2015-08-24 72 views
0

是否可以在使用LIKE語句對另一列進行分組時求和?Transact SQL:SUM與LIKE陳述

Ex。我需要按部門合併總勞動時間(類似「勞動法」):

Code Hours 
L0101 5.25 
L0104 39 
L0201 60.5 
L0202 95.5 
L0203 65 
L0204 44.5 
L0301 24 
L0302 70 
L0303 121.5 
L0305 119 

results: 
L0100s 44.25 
L0200s 265.5 
L0300s 334.5 
+1

'GROUP BY SUBSTRING ...' – Mihai

回答

1

這不是使用like,而是顯示您顯示的結果。

Select 
    Substring(code,1,2) as Code3, Sum(Hours) as TotalHours 
from table 
group by 
    Substring(code,1,2) 
1

你必須重複功能,通過組得到你想要的東西:勞動法的第一個3個字母

select left(Code,3) + '00s' as Department, 
     sum(Hours) as Hours 
from Table 
group by left(Code,3) + '00s' 
1

組:

SELECT  LaborCode = LEFT(Code, 3) + '00s', 
      TotalHours = SUM([Hours]) 
FROM  my_table 
GROUP BY LEFT(Code, 3) 
+0

這是完美的! tyvm – SarahSQL