简体   繁体   中英

DISTINCT WITH SUM

I have a mysql join result which looks like this.

ID | Name | Score | SomeID
---------------------------
1  | abc  |  100  |  2 
1  | abc  |  100  |  2
1  | abc  |  100  |  3
1  | abc  |  100  |  3
1  | abc  |  100  |  4
1  | abc  |  100  |  4

I want the result of this join result in sum as distinct Like

ID | Name | SUM(Score) | SomeID
---------------------------
1  | abc  |    200     |  2
1  | abc  |    200     |  3
1  | abc  |    200     |  4

Is there any possible solution to this problem! Any Help?

Try this:

SELECT ID, Name, SUM(Score), SomeID
FROM tableA 
GROUP BY ID, Name, SomeID;

You need sum and group by

select
id,
name,
sum(Score) as total,
SomeID
from table_name
group by Name,SomeID

UPDATE : Mysql has flexibility to have columns in the selection while using the aggregate function and then not using them in group by

But many RDBMS will not like it and in that case you must add them in group by clause. So as a standard it should be as -

group by id, Name,SomeID

Try this:

  SELECT ID,
         Name,
         SUM(Score) total,
         SomeID
    FROM table1
GROUP BY ID,
         Name, 
         SomeID

You can check a demo on SQLFiddle here .

Try using group by clause in your query. Group your query by SomeId in your result set to get the desired output

Use Group by Clause

select
id,
name,
sum(Score) as total,
SomeID
from table_name
group by name,SomeID,ID

If you are just trying to produced the above, then you are basically trying to do:

SELECT 
id, name, sum(score), some_id
FROM table1
group by id, name,some_id

As you have stated, this isn't a table but a join result. If the join result looks something like (could be anything).

SELECT table1.id, table2.name, table2.score, table1.some_id
FROM table1 JOIN table2 ON table1.id=table2.table1_id

All you need to do is wrap is query with a join and give it an alias.

SELECT 
x.id, x.name, x.sum(score), x.some_id
FROM 
(SELECT table1.id, table2.name, table2.score, table1.some_id
FROM table1 JOIN table2 ON table1.id=table2.table1_id) x
GROUP BY x.id, x.name, x.some_id

You just use aggregate function of database:

 SELECT ID, Name,SUM(Score) as "SUM(Score)",SomeID
 FROM table_name
 GROUP BY ID,Name,SomeID
 ORDER BY 4;

Things are this simple:

SELECT ID, Name,SUM(Score),SomeID
 FROM table_name
 GROUP BY SomeID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM