Get the sum of the column in mysql - php

Below is the table I have created, my goal is to get the sum of the value depending of each person has, and exclude any username duplicate.
username | value
Bob 5
Vicky 10
Bob 12
Desire results:
username | value
Bob 17
Vicky 10

This is what the GROUP BY clause do, use GROUP BY username with SUM(value):
SELECT username, SUM(value)
FROM tablename
GROUP BY username;
SQL Fiddle Demo
When you add a GROUP BY clause, rows that have the same values in the list of columns you specify in it, will be gathered into a group of unique values. For the other columns that are not listed in the GROUP BY clause, the aggregate function will be applied to it, the SUM(value) in the query above.

Try this
SELECT T.username, SUM(T.value) AS value
FROM your_table_name T
WHERE T.username IS NOT NULL
GROUP BY T.username

Try This one
SELECT username, SUM(value) as val FROM tablename GROUP BY username;

Use the following query:
SELECT url, SUM(pos) FROM import_images GROUP BY url

Related

Trying to write count query loop based on a different table printing

I have two tables:
access(name, id, check, key)
events(name, key, event_name)
I am trying to print some things from these tables into a php/html table with these columns:
name, key, event_name, access count
My trouble being I would like each event to display the "count" of access rows that have the same key.
Event table example:
name key event_name
test 1 first
joe 2 second
And the access table...
name id check key
test 123 yes 1
test 1235 yes 1
joe 175 yes 2
joe 852 yes 2
test 5843 yes 1
test 123455 yes 1
The resulting table I am hoping to look like this:
name key event_name access count
test 1 first 4
joe 2 second 2
Does anybody know how to do this? I've gotten to this but it obviously doesn't work because the key isn't given to the inner select query...
select event_name, name, key,
(SELECT COUNT(key) FROM access WHERE key=key AND name=name)
from event;
Thank you to anyone who takes a look and might have any ideas! I've been staring at this and w3schools for hours
At present your subquery will return a count of all rows as it is not correlated to the main query, so both occurrences of key in key=key will refer to the same column and the expression will always be true (likewise for name). To correlate the subquery, add table references:
select event_name, name, key,
(SELECT COUNT(key) FROM access a WHERE a.key=e.key AND a.name=e.name) AS `access count`
from event e
You can also get the same results with a join and aggregattion:
select e.name, e.key, e.event_name, count(*) access_count
from event e
left join access a on a.key = e.key and a.name = e.name
group by e.name, e.key, e.event_name

MySQL Table - Display name once along with their total score

I have the below data entered into a database from a website:
USER | SCORE
abc | 4
ghi | 2
abc | 6
def | 1
abc | 3
I want to now display a list of all the users, in alphabetical order, without repeating itself, and their total score. So with the table above, it would look something like:
abc: 13
def: 1
ghi: 2
How do I do that? I would use php, right? Or javascript?
User the Query to fetch data from database
SELECT USER,
SUM (SCORE) as SCORE
FROM table
GROUP BY USER ORDER BY USER ASC;
You should use PHP to fetch data from DB and print.
Your query will be something like:
select user, sum(score) as total_score from table group by user order by user asc;
It can be done in MySQL without involving any other programming language.
The following should do the trick using MySql query:
SELECT USER , SUM(SCORE) FROM table GROUP BY USER ORDER BY USER ASC
You can do this in database itself using the below SQL query.
SELECT SUM( SCORE ) , USER
FROM SampleTable
GROUP BY USER
ORDER BY USER
Try this:
SELECT User, SUM(Score) as Total_Score
FROM TableName
GROUP BY User
ORDER BY User;
No need to use javascript or php to achieve it. SQL is powerful enough to achieve it alone.
You need to fetch data from table and iterate through it. Below is SQL:
SELECT User, SUM(Score) as total
FROM TABLE_NAME
GROUP BY User
ORDER BY User;

Mysql SELECT name where all rows with the name have certain values

How would I write a query that would select the name of a person (a column in the row) given that they have enough rows to meet all conditions?
For example, I have a database set up like so:
name permission_id
Bob 1
Bob 2
Jerry 3
Jerry 1
Jose 2
Billy 1
Billy 2
How would I only select the people that have permission id 1 and 2? In other words, I would like a query that checks every person by name to see if they have all the permissions requested.
In this example if I was to check for all users to who have permission 1 and 2 I should get Bob and Billy as a return value.
Here is my current query:
$this->db->select('center_user_permissions.id, center_users.first_name, center_users.last_name');
$this->db->from('center_user_permissions');
$this->db->where_in('permission_id', $permission_ids);
$this->db->join('center_users', 'center_users.center_id = center_user_permissions.center_id');
Currently this query returns anybody who has either permission id 1 or 2. I need it to be 1 AND 2. But I know I can't simply make two wheres because one particular row can't have both permission ids, but the query must check all rows for the specified ids.
I believe I would need a SELECT statement inside of my where? Can anybody tell me if I'm thinking correctly? Thanks.
You can use a in clause an an having for check that the user has both the permission
select name
from center_user_permissions
where permissions_id in (1,2)
group by name
having count(*) = 2
I'm not sure how to build this query in CodeIgniter, but you could INNER JOIN for each permission ID you want the user to have:
SELECT center_users.center_id, center_users.first_name, center_users.last_name
FROM center_users
INNER JOIN center_user_permissions AS p1 ON p1.center_id=center_users.center_id AND p1.permission_id=1
INNER JOIN center_user_permissions AS p2 ON p2.center_id=center_users.center_id AND p2.permission_id=2
You could check for more permissions by adding a INNER JOIN for each additional permission you wanted to require.
MySQL's GROUP BY and HAVING
Not user what kind of DB interface you're using in $this->db, but it may make things a little tricky. If I start with a raw SQL query:
SELECT
center_user_permissions.id,
center_users.first_name,
center_users.last_name
FROM center_user_permissions
LEFT JOIN center_users
ON center_users.center_id = center_user_permissions.center_id
WHERE center_user_permissions.permission_id in (1,2)
Group by name, where count of permission_id is > 1
This will group rows by first_name (so you'll only get one row for each unique name). Doing do allows you to run aggregate functions (SUM(), MAX(), COUNT()) against the rows that were "grouped" into a single row.
SELECT
center_user_permissions.id,
center_users.first_name,
center_users.last_name
FROM center_user_permissions
LEFT JOIN center_users
ON center_users.center_id = center_user_permissions.center_id
GROUP BY center_users.first_name
WHERE center_user_permissions.permission_id in (1,2)
HAVING COUNT(center_user_permissions.permission_id)>1
select distinct(name),.. as name from 'center_user_permissions',center_users where
center_users.center_id = center_user_permissions.center_id and permissions_id in (1,2)
substitute .. with your other fields and put in distinct the value that you want to be unique

How to group the column value using PHP and MySQL

I need one help.I need query to skip duplicate column value according to the auto increment id using MySQL.I am explaining my table structure below.
db_subcat:
member_id day_id
16 2
18 2
18 2
18 3
Here i need to skip the duplicate column value according to the member_id e.g- here for member_id-18 there are two day_id as 2,i need to fetch only one if member_id is same.
you can use distinct:
select distinct member_id, day_id from db_subcat;
you can use distinct as well as group by
select distinct member_id, day_id from db_subcat;
select member_id, day_id from db_subcat group by member_id, day_id;
Here distinct will be faster than group by. To see the difference have a look at http://charlesnagy.info/it/mysql/difference-between-distinct-and-group-by
You can use the UNIQUE key in MySQL so that the duplicate results will not be inserted in the first place.
Else, you can use SELECT distinct:
SELECT distinct member_id, day_id from db_subcat;
More information on SQL Unique Constraint: http://www.w3schools.com/sql/sql_unique.asp.
More information on SQL Select Distinct: http://www.w3schools.com/sql/sql_distinct.asp.
Apart from skipping the duplicate member id, you may want the sum of day_id as well, below query fetches that:
select member_id, sum(day_id)
from db_subcat
group by member_id
You can use any aggregate function (e.g. min, max, count, avg) according to the requirement.

Select users with more than one instance in database

I have a table with a userID field and an itemID field. I would like to select all of those users that have two or more instances where itemID is the same (that is, if for example there are 3 records where userID = 1 and itemID = 7 then I would like those results, but not if there's just one instance). I need to get all users (not just results for a certain userID).
Can anybody suggest how I could do this?
Thanks.
You can do this using aggregation and a having clause. If you just want the users:
select distinct userID
from t
group by userId, itemID
having count(*) >= 2;
This is an interesting query because it is one of the very rare situations where group by and select distinct are used together. If you wanted the userId/itemId pairs, then you would use select userId, itemId, without the distinct.
You just need to use group by and having. The having clause is like where except that it also works on aggregations. So it's something like select userID, itemID, count(*) from mytable group by userID, itemID having count(*) > 1.

Categories