How to get Mysql SUM of multiple columns in database

Sebastian Farham

I want to calculate total products in cart for one user by summing values for each product in cart.

I'm using this query :

    SELECT *, SUM(quantity) OVER (PARTITION BY product_id ORDER BY id) AS TotalProducts 
    FROM cart WHERE user_id ='$user_id';

Getting error:

SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(PARTITION BY product_id ORDER BY id)

EDIT with DB schema

id | product_id | quantity | user_id
1  | 37         | 2        | 23847
2  | 70         | 2        | 23847

I can't see what I'm doing wrong?

Sloan Thrasher

I'm not familiar with the MariaDB syntax, and you didn't show your schema, but here's my shot at an answer:

SELECT c.*,
    SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id

Or, if you want a total per product, you could use:

SELECT c.*,
    SUM(c.quantity) as `TotalProducts`
FROM cart c
WHERE c.user_id = '$user_id'
GROUP BY c.user_id, c.product_id

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Get Sum of score of a team which is present in multiple rows and two columns MySql PHP

MYSQL sum of multiple columns returns null

Pandas - dataframe groupby - how to get sum of multiple columns

How to get all the result columns from database with other custom(concat, sum, count) columns in Jooq

Get the sum of multiple columns

How get multiple SUM() for different columns with GROUP BY

MySQL get multiple rows into columns

Pandas : Sum multiple columns and get results in multiple columns

How to get mysql sum multiple column with where clause?

How do I get the sum of multiple columns dynamically?

Mysql get count on multiple columns

sum same condition in multiple columns to get a total

Mysql : how i can get 3 columns from multiple tables?

How to get total of multiple columns from sum of quantity and average of price?

How to use MySql SUM() on multiple columns

sum multiple columns of same table in mysql

MySQL : How to get the sum columns by name of alias

MySQL query to get multiple columns to 3 columns

how to sum multiple columns into one result from database in php? is that posible?

MySQL Sum total using Group By multiple columns

Querying multiple columns in a database and finding their sum

how to get for multiple columns

Get rows with maximum sum of 3 columns - Mysql

Sum, Subtract and Join of multiple mysql table columns

How to count the rows from multiple tables in MYSQL and get a sum of it?

Pandas - How to get get sum of rows by multiple columns in a DataFrame

How to get the min, max and sum of all columns in the database?

How to get the sum of multiple columns of a datatable in c#

Cumulative sum in MYSQL based on multiple columns