2011-05-12 40 views
7

我在SQL-server中有一個表,其中的projectcodes和子項目代碼在相同的字段中。我該怎麼做`group by`部分匹配

的stucture是這樣

+----+------+-------------+-------+--------+--------+ 
| id | date | projectcode | debit | credit | budget | 
+----+------+-------------+-------+--------+--------+ 
| 1 | bla | A100  | bla 
| 2 | bla | A100.01  | 
| 3 | bla | A112  | 
| 4 | bla | A112.02 

我如何做一個選擇這樣

SELECT projectcode 
    , sum(debit) as debit 
    , sum(credit) as credit 
    , sum(budget) as budget 
FROM table1 
GROUP BY -insert-answer-here- 

我所要的輸出group by A100和A100.01和A100.x在一起,以及如A112 + A112.x

我該怎麼做?

我無法控制表的結構。

回答

11
GROUP BY LEFT(projectcode ,CHARINDEX('.',projectcode + '.')-1) 
1

如果項目的代碼始終遵循相同的模式(cnnn/cnnn.nn),你可以得到的前四個字符:

group by substring(projectcode, 1, 4) 
+0

前綴長度('A100'等)不同。 – Johan 2011-05-12 12:19:24

+0

@Johan:好的,那麼你需要使用'charindex'來定位字符串中的句點,正如馬丁所示。 – Guffa 2011-05-12 12:52:46

0

也許這會工作:

SELECT Substring(projectcode, 1, 4) as Project 
    , sum(debit) as debit 
    , sum(credit) as credit 
    , sum(budget) as budget 
FROM table1 
GROUP BY Substring(projectcode, 1, 4) 
+0

您不能使用輸出值進行分組,您必須在兩個位置指定表達式。 – Guffa 2011-05-12 12:01:03

+0

@Guffa:它在sqlite中工作;我的錯。 – alex 2011-05-12 12:01:42