Find multiple totals by adding values from mysql table - mysql

I need to create a number adding all the values i can find in the db related to a specific customer.
Ex.
| Cust. | Value |
| 1 | 3 |
| 2 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 5 |
The result i want is : Customer #1 = 4, Customer #2 = 2; Customer #3 = 5.
There is a way to do that right into the mysql query?

Try Below query.
Select CONCAT('Customer #' , cust) as customer , sum(Value)
FROM customer_table
Group By cust

You want to SUM the values with a specific GROUP BY clause. Think of the GROUP BY as dividing rows into buckets and the SUM as aggregating the contents of those buckets into something useful.
Something like:
SELECT SUM(Value) FROM table GROUP BY Cust

Related

Mysql IN function

class_table
+----+-------+--------------+
| id |teac_id| student_id |
+----+-------+--------------+
| 1 | 1 | 1,2,3,4 |
+----+-------+--------------+
student_mark
+----+----------+--------+
| id |student_id| marks |
+----+----------+--------+
| 1 | 1 | 12 |
+----+----------+--------+
| 2 | 2 | 80 |
+----+----------+--------+
| 3 | 3 | 20 |
+----+----------+--------+
I have these two tables and i want to calculate the total marks of student and my sql is:
SELECT SUM(`marks`)
FROM `student_mark`
WHERE `student_id` IN
(SELECT `student_id` FROM `class_table` WHERE `teac_id` = '1')
But this will return null, please help!!
DB fiddle
Firstly, you should never store comma separated data in your column. You should really normalize your data. So basically, you could have a many-to-many table mapping teacher_to_student, which will have teac_id and student_id columns.
In this particular case, you can utilize Find_in_set() function.
From your current query, it seems that you are trying to getting total marks for a teacher (summing up marks of all his/her students).
Try:
SELECT SUM(sm.`marks`)
FROM `student_mark` AS sm
JOIN `class_table` AS ct
ON FIND_IN_SET(sm.`student_id`, ct.`student_id`) > 0
WHERE ct.`teac_id` = '1'
In case, you want to get total marks per student, you would need to add a Group By. The query would look like:
SELECT sm.`student_id`,
SUM(sm.`marks`)
FROM `student_mark` AS sm
JOIN `class_table` AS ct
ON FIND_IN_SET(sm.`student_id`, ct.`student_id`) > 0
WHERE ct.`teac_id` = '1'
GROUP BY sm.`student_id`
Just in case you want to know why, The reason it returned null is because the subquery returned as '1,2,3,4' as a whole. What you need is to make it returned 1,2,3,4 separately.
What your query returned
SELECT SUM(`marks`)
FROM `student_mark`
WHERE `student_id` IN ('1,2,3,4')
What you expect is
SELECT SUM(`marks`)
FROM `student_mark`
WHERE `student_id` IN (1,2,3,4)
The best way is it normalize as #madhur said. In your case you need to make the teacher and student as one to many link
+----+-------+--------------+
| id |teac_id| student_id |
+----+-------+--------------+
| 1 | 1 | 1 |
+----+-------+--------------+
| 2 | 1 | 2 |
+----+-------+--------------+
| 3 | 1 | 3 |
+----+-------+--------------+
| 4 | 1 | 4 |
+----+-------+--------------+
If you want to filter your table based on a comma separated list with ID, my approach is to
append extra commas at the beginning and at the end of a list as well as at the beginning and at the end of an ID, eg.
1 becomes ,1, and list would become ,1,2,3,4,. The reason for that is to avoid ambigious matches like 1 matches 21 or 12 in a list.
Also, EXISTS is well-suited in that situation, which together with INSTR function should work:
SELECT SUM(`marks`)
FROM `student_mark` sm
WHERE EXISTS(SELECT 1 FROM `class_table`
WHERE `teac_id` = '1' AND
INSTR(CONCAT(',', student_id, ','), CONCAT(',', sm.student_id, ',')) > 0)
Demo
BUT you shouldn't store related IDs in one cell as comma separated list - it should be foreign key column to form proper relation. Joins would become trivial then.

MySQL count unique and duplicate values

I need some help with counting both unique and duplicate values in MySQL. I want to know how many records there are total, and also how many is there two times and three times and so on...
Do I need to use UNION or something? I think SUM would be the best solution for me because of I might use some joins with this in future.
Sample data:
| custId | name |
|--------|--------|
| 1001 | Alex |
| 1001 | Alex |
| 1002 | Daniel |
| 1003 | Mark |
| 1002 | Daniel |
Sample results:
| total | twoTimes | threeTimes |
|-------|----------|------------|
| 3 | 2 | 0 |
Thanks in advance.
Just a basic group by should do it
SELECT YourValue, Count(YourValue)
FROM YourTable
GROUP BY YourValue
If you want only a category, like unique values ADD
HAVING Count(YourValue) = 1
Here is my approach:
http://sqlfiddle.com/#!9/9411dc/3
SELECT c.cnt AS `times`, COUNT(c.name) cnt
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c
GROUP BY c.cnt;
that is not exactly what you did ask (you asked for pivot table which is very difficult to realize). So if you want to make it pivot you can read here: MySQL pivot table
And if you are sure that you have very small max of duplicate count your pivot query could be:
http://sqlfiddle.com/#!9/9411dc/5
SELECT
SUM(IF(c.cnt=1,1,0)) AS `Unique`,
SUM(IF(c.cnt=2,1,0)) AS `Two times`,
SUM(IF(c.cnt=3,1,0)) AS `Three times`,
SUM(IF(c.cnt=4,1,0)) AS `Four times`
FROM (SELECT name, COUNT(custId) cnt
FROM cust
GROUP BY name) c

SUM after COUNT and Group By MYSQL

I want to ask about SQL in mysql. Im stack over 1 hour :(
I have sql :
SELECT TZL.IsMissed, COUNT(TZL.ChatID) as Amount FROM tblLog TZL group by TZL.IsMissed
And the result :
| IsMissed | Amount |
| 0 | 100 |
| 1 | 500 |
I want add one more column after Amount column, let say the name of new column is SumAmount. i want SumAmount value is SUM of the Amount Column.
| IsMissed | Amount | SumAmount |
| 0 | 100 | 600 |
| 1 | 500 | 600 |
I already try sql like below :
SELECT
tbl.*,SUM(tbl.Amount) as SumAmount
FROM
(
SELECT
TZL.IsMissed,
COUNT(TZL.ChatID) AS Amount
FROM
tblLog TZL
GROUP BY
TZL.IsMissed
) tbl
GROUP BY
tbl.IsMissed
WITH ROLLUP
But with ROLLUP the result is add a new one row, not column. Anyone can teach me for this ?
Thanks for answer
There are several ways to approach this. I would calculate the value in the from clause:
SELECT TZL.IsMissed, COUNT(TZL.ChatID) as Amount, tt.SumAmount
FROM tblLog TZL CROSS JOIN
(SELECT COUNT(*) as SumAmount FROM tblLog) tt
GROUP BY TZL.IsMissed, tt.SumAmount;

MySQL Join two tables with condition

Based on these two tables:
products
| ID | Active | Name | No
--------------------------------------------------
| 1 | 1 | Shirt | 100
| 2 | 0 | Pullover | 200
variants
| MasterID | Active | Name | No
--------------------------------------------------
| 1 | 1 | Red | 101
| 1 | 0 | Yellow | 102
I want to get every product which is active and also their active variants in one sql.
Relation between those tables MasterID -> ID
Needed result:
ID (master) | Name | No
--------------------------------------------------
1 | Shirt | 100
1 | Red | 101
I tried it with using union, but then I am not able to get the belonging MasterIDs.
It looks like you just need a simple join:
select *
from products
left join variants
on products.ID = variants.MasterID
where products.Active = 1
and variants.Active = 1
Update after requirements were made clearer:
select ID, Name, No, 'products' as RowType
from products
where Active = 1
union
select variants.MasterID as ID, variants.Name, variants.No, 'variants' as RowType
from products
join variants
on products.ID = variants.MasterID
where products.Active = 1
and variants.Active = 1
order by ID, RowType, No
I've assumed you want the results ordered by ID, with products followed by variants. The No column may order it this way implicitly (it's impossible to know without real data), in which case the RowType column can be removed. The order by clause might need to be altered to match your specific RDBMS.
This should gives you the expected result:
select * from products left join variants on products.id = variants.masterId
where products.active=1 and variants.active=1
If not please add the expected result to your question.

Values in same row of groupwise maximum

I've got a table with the most common colors in images. It looks something like this:
file | color | count
---------------------
1 | ffefad | 166
1 | 443834 | 84
2 | 74758a | 3874
2 | abcdef | 228
2 | 876543 | 498
3 | 543432 | 3382
3 | abcdef | 483
I'm trying to get the most common color for each image. So I'd like my result to be:
file | color | count
---------------------
1 | ffefad | 166
2 | 74758a | 3874
3 | 543432 | 3382
So my problem seems to be that I need to GROUP BY the file column, but MAX() the count column. But simply
SELECT h.file, h.color, MAX(h.count) FROM histogram GROUP BY h.file
isn't working because it's indeterminate, so the color result won't match the row from the count result.
SELECT h.file, h.color, MAX(h.count) FROM histogram GROUP BY h.file, h.color
fixes the determinacy, but now every row is "unique" and all rows are returned.
I can't figure out a way to do a subquery or join, since the only "correct" values I can figure to get, file and count, are not distinct by themselves.
Perhaps I need a saner schema? It's "my" table so I can change that if need be.
SELECT tbl.file, tbl.color, tbl.count
FROM tbl
LEFT JOIN tbl as lesser
ON lesser.file = tbl.file
AND tbl.count < lesser.count
WHERE lesser.file IS NULL
order by tbl.file
select file , max(count)
FROM histogram
GROUP BY h.file
This will give the max(count) by file. Turn it into a subquery and inner join so it acts as a filter.
select h.file, h.colour, h.count
from histogram inner join
(select file , max(count) as maxcount
FROM histogram
GROUP BY h.file) a
on a.file = h.file and a.maxcount = h.count
This will respond with 2 rows if there are more than 1 colour with the same max count.