SQL group by

If I have a recordset

name    amount    Code
Dave    2         1234
Dave    3         1234
Daves   4         1234

I want this to be grouped based on code and name, but the last Row has a typo in the name, so this group will not.

What would be the best way to group them as:

Dave/Daves 9 1234

+3
source share
5 answers

Generally, if the data is incorrect, you should correct the data.

However, if you want to make a report anyway, you can come up with another criterion for grouping, for example, LEFT (Name, 4) will group by the first 4 characters of the name.

CASE (CASE WHEN name = 'Daves' THEN 'Dave' ELSE name), , - .

+5

,

SELECT cname, SUM(amount)
FROM (
  SELECT CASE WHEN NAME = 'Daves' THEN 'Dave' ELSE name END AS cname, amount
  FROM mytable
)
GROUP BY cname

, .

+4

? .

, "" .

, , , ( - ) , , " ", , .

+1

MySQL:

select
  group_concat(distinct name separator '/'),
  sum(amount),
  code
from
  T
group by
  code

MSSQL 2005+ group_concat() .NET.

+1

, , - , -. , , , , , .

, , , . 100%.

, .

+1

Source: https://habr.com/ru/post/1703814/


All Articles