How do I do `group by` partial match

馋奶兔 提交于 2020-01-03 08:57:04

问题


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.


回答1:


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



回答2:


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)



回答3:


Maybe this would work:

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)


来源:https://stackoverflow.com/questions/5977506/how-do-i-do-group-by-partial-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!