2

I need to merge 2 records into one.

Mine table:

 ╔═════╦═══════╦═════╦═══════╗
 ║ id* ║ name  ║price║ rank  ║
 ╠═════╬═══════╬═════╬═══════╣
 ║  0  ║   A   ║ 12  ║  CAP  ║
 ║  1  ║   B   ║ 32  ║  BAC  ║
 ║  2  ║   B   ║ 13  ║  BAC  ║
 ╚═════╩═══════╩═════╩═══════╝

and after merge (same table NOT SELECT)

 ╔═════╦═══════╦═════╦═══════╗
 ║ id* ║ name  ║price║ rank  ║
 ╠═════╬═══════╬═════╬═══════╣
 ║  0  ║   A   ║ 12  ║  CAP  ║
 ║  1  ║   B   ║ 45  ║  BAC  ║
 ╚═════╩═══════╩═════╩═══════╝

looking for records that name, and rank is the same like one another and SUM price.

Merge database, and REMOVE second duplicated record.

I need to make it using Join statement or is there any faster method to do this?

Rafał Figura
  • 5,428
  • 1
  • 15
  • 20

5 Answers5

0
SELECT name,   
SUM (price), rank
FROM tablename   
GROUP BY name, rank;  

This query provides you the information needed. For more info check: http://www.w3resource.com/sql/aggregate-functions/sum-with-group-by.php

Jur Clerkx
  • 698
  • 4
  • 14
0

Try this:

SELECT MIN(id),name,sum(price) as price,rank,   
SUM (price)   
FROM tablename   
GROUP BY name, rank;
Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
0

Try this,

select name,
           SUM(price),
          @rownum := @rownum + 1 AS rank
    from your_table
    cross join (select @rownum := 0) r
    group by name

Counter for rank came from this post : select increment counter in mysql

Edit : I tried it using SQL fiddle Schema :

CREATE TABLE name_table
(
id int,
name varchar(5),
price decimal(10),
rank int
);

insert into name_table values(0, 'A', 12, 1);
insert into name_table values(1, 'B', 32, 2);
insert into name_table values(2, 'B', 13, 2);

Query :

select    id,
          name,
          SUM(price),
          @rownum := @rownum + 1 AS rank
    from name_table
    cross join (select @rownum := 0) r
    group by name

Result :

id  name price rank
0   A     12    1
1   B     45    2
Community
  • 1
  • 1
Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
0

Just try this

I think below is a way by which you can achieve your output

SELECT name, SUM (price), rank FROM `yourtablename` GROUP BY name, rank;
Nikunj Soni
  • 854
  • 1
  • 5
  • 18
0

This appears to be what you're after...

SELECT MIN(id) id 
     , name
     , SUM(price) price 
     , rank 
  FROM my_table 
 GROUP 
    BY name
     , rank;
Strawberry
  • 33,750
  • 13
  • 40
  • 57