Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rows that have same value in a column, sum all values in another column and display 1 row

Tags:

sql

Example Table user:

    ID | USER_ID | SCORE | 
    1  |  555    |   50  | 
    2  |  555    |   10  |
    3  |  555    |   20  |
    4  |  123    |   5   |
    5  |  123    |   5   |
    6  |  999    |   30  |

The result set should be like

ID | USER_ID | SCORE | COUNT |
1  |  555    |   80  |   3   |
2  |  123    |   10  |   2   |
3  |  999    |   30  |   1   |

Is it possible to generate a sql that can return the table above, so far I can only count the rows where certain user_id appear, but don't know how to sum and show for every user ?

like image 483
Milos Nikolik Avatar asked Jan 30 '17 13:01

Milos Nikolik


People also ask

How do you sum a column in Excel based on a value in another column?

If you want, you can apply the criteria to one range and sum the corresponding values in a different range. For example, the formula =SUMIF(B2:B5, "John", C2:C5) sums only the values in the range C2:C5, where the corresponding cells in the range B2:B5 equal "John."

How do I sum a column in Excel based on two different columns?

(1) Select the column name that you will sum based on, and then click the Primary Key button; (2) Select the column name that you will sum, and then click the Calculate > Sum. (3) Click the Ok button.

How do you sum matching values from multiple rows in Microsoft Excel?

Sum a range of cells -- SUM Function The quickest and easiest way to sum a range of cells is to use the Excel AutoSum button. It automatically enters an Excel SUM function in the selected cell. The SUM function totals one or more numbers in a range of cells.

How do you find rows which has same value in a column in Excel?

Highlight Duplicate Rows Using Conditional Formatting Select the Excel Conditional Formatting drop-down menu from the Home tab at the top of your Excel workbook. Within this menu: Select the Highlight Cells Rules option and from the secondary menu that appears, select the Duplicate Values... option.


1 Answers

You've included a column called "ID" in both the source data and desired results, but I'm going to assume that these ID values are not related and simply represent the row or line number - otherwise the question doesn't make sense.

In which case, you can simply use:

SELECT
   USER_ID,
   SUM(SCORE) AS SCORE,
   COUNT(USER_ID) AS COUNT
FROM 
  <Table>
GROUP BY
   USER_ID

If you really want to generate the ID column as well, then how you do this depends on the database platform being used. For example on Oracle you could use the ROWNUM pseudocolumn, on SQL Server you will need to use ROW_NUMBER() function (which also works for Oracle).

like image 56
Nathan Griffiths Avatar answered Oct 15 '22 15:10

Nathan Griffiths