Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do `group by` partial match

I have a table in SQL-server with projectcodes and sub-project-codes in the same fields.

The stucture is something like this

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

How do I do a select like this

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

I want the output to group by A100 and A100.01 and A100.x together as well as A112 + A112.x

How do I do this?

I have no control over the structure of the table.

like image 689
Johan Avatar asked May 12 '11 11:05

Johan


2 Answers

GROUP BY LEFT(projectcode ,CHARINDEX('.',projectcode  + '.')-1)
like image 135
Martin Smith Avatar answered Oct 25 '22 09:10

Martin Smith


If the project code always follows the same pattern (cnnn / cnnn.nn) you can just get the first four characters:

group by substring(projectcode, 1, 4)
like image 36
Guffa Avatar answered Oct 25 '22 08:10

Guffa