我怎么做'分组'部分匹配

时间:2011-05-12 11:50:02

标签: sql-server group-by

我在SQL-server中有一个表,其中包含相同字段中的项目代码和子项目代码。

结构是这样的

+----+------+-------------+-------+--------+--------+
| 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

我该怎么做?

我无法控制桌子的结构。

3 个答案:

答案 0 :(得分:11)

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

答案 1 :(得分:1)

如果项目代码始终遵循相同的模式(cnnn / cnnn.nn),您可以获得前四个字符:

group by substring(projectcode, 1, 4)

答案 2 :(得分: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)