PHP/MySQL total by member - php

Like this a result :
75 Ansari 5 10
88 Koodoo 4 0
90 Koodoo 14 0
83 Koodoo 5 0
82 Koodoo, 6 0
81 Koodoo 4 0
79 Koodoo 5 0
74 Savage 1 0
80 Strike 2 36
87 Strike 4 15
78 Sullivan 3 15
77 Sullivan 2 0
I would like to get the total for each member for the last 2 columns (Hours and Minutes).
My query look like that :
SELECT
*
FROM
$tbl_name
ORDER BY
player
If someone would have a quick fix for that I would appreciate it.

Probably you want something like this (but you didn't provide a schema so I'm guessing on the field names).
SELECT `id`, `player`, SUM(`hours`) as hours, SUM(`minutes`) as minutes FROM `$tbl_name` GROUP_BY `player`;

You need to GROUP BY the user's name and SUM the totals for the hours and minutes columns.
A Simple example of this is:
SELECT `id`,
`user`,
SUM(`hours`) as tot_hours,
SUM(`mins`) as tot_mins
FROM `test`
GROUP BY `user`;
You can see this example run at this SQLFiddle
Note: With that fiddle, I removed the extra comma in this line (I assumed it was a typo)
82 Koodoo, 6 0
If that comma is supposed to be there, you just need to adjust that one insert statement to add the comma within the quotes of the name. That will adjust your query outcome as Koodoo, won't group with the other Koodoo values.

Related

Sorting in MySQL/

I have a problem trying to work out some logic when trying to sort. Even went back to Excel to work out simple logic.
What I have is :-
ColA ColB
100022 33
100022 36
100024 28
100024 32
100024 41
100024 52
100026 38
100038 28
100038 42
100038 48
100038 59
What I want to do is sort by Column B (heightest to lowest) BUT I dont want Column A to have the same values next to each other.Sorting the above will have 33 & 36 (with 100022) next to each other (and 42&48) with 100038 next to each other. As long as Column B is sorted as best it can from heightest to lowest and Column A's values are never next to each other (Unless absolutely necessary) I'm happy.
Ideally I am after a logic to end up with something like this ..
100024 28
100038 28
100022 33
100024 32
100022 36
100026 38
100038 42
100024 41
100038 48
100024 52
100038 59
Any help or ideas would be greatly appreciated.
Thank you
Brad
If you want to enforce that no two values from ColA appear adjacent, then one option would be to assign a row number to each value in a given ColA block, and then order to ensure that adjacent values do not occur.
SET #row_number = 0;
SET #ColA = NULL;
SELECT t.ColA, t.ColB
FROM
(
SELECT
#row_number:=CASE WHEN #ColA = ColA THEN #row_number + 1 ELSE 1 END AS rn,
#ColA:=ColA AS ColA,
ColB
FROM
yourTable
ORDER BY ColA, ColB DESC
) t
ORDER BY t.rn, t.ColB DESC
You mentioned in your question that wanted ColB sorted from highest to lowest, which I have done. If you want ascending ordering, just remove the DESC from the above query.
Output:
Demo here:
Rextester

How to get row of the table with maximum value

I have a table as follow :
id date custid billno month amount balance
64 07-Jun-2015 1 102 5 9192 0
134 05-Jul-2015 1 172 6 9744 0
235 01-Aug-2015 1 277 7 4032 0
435 04-Sep-2015 1 461 8 3024 0
747 22-Sep-2015 1 597 9 2875 0
958 06-Nov-2015 1 789 10 3100 0
I want to get the row which has month max i.e. I want to get the row with month 10
If I use the following query then it gives the row with month 9
$get_lst = mysql_query("select * from `ledger` where `custid`='$custid' order by `month` DESC") or die(mysql_error());
$get_lst = mysql_fetch_assoc($get_lst);
print_r($get_lst);
Please help me what I am missing in the query ?
It looks like you are storing your values with the wrong type. The Date column should be type of DATE and your month column should be type of INT or even better TINYINT.
Storing month as VARCHAR causes the db to sort it as string. Ordering strings will start checking char by char (comparing '9' with '10' will result in '9' > '1').
After changing your column to either INT or TINYINT your query will work.
To increase the performance for larger tables, you could also use "LIMIT 1" in your query, in that way you won't fetch the whole table, if you only need one row.

inserting values to new table in mysql_query

Okay guys, I will try to share my guestion understandable. So I have 2 tables like below:
ALL Id from TABLES are Autoincrement.
Number
id number
10 100
11 102
12 105
13 106
subnumber
id number_id subnumber
52 10 10
53 11 15
54 13 40
You see some numbers (not all) have subnumbers. I mean:
From table number the number where id = 13 has subnumber and it is equal to 40.
I want to save this table in another table.
$sql1=mysql_query('SELECT number FROM number');
$while(fetch1=mysql_fetch_array($sql1))
{
mysql_query('
INSERT INTO `save_number` (number)'
VALUES ('.$fetch1['number'].');
);
}
save_number
id number
100 100
101 102
102 105
103 106
Now i gonna save table (subnumber) in another table (save_subnumber)
$sql2=mysql_query('SELECT number_id, subnumber FROM subnumber');
$while(fetch2=mysql_fetch_array($sql2))
{
mysql_query('
INSERT INTO `save_subnumber` (number_id, subnumber)'
VALUES ('.$fetch2['number_id'].', '.$fetch2['number'].');
);
}
save_subnumber
id number_id subnumber
60 10 10
61 11 15
62 13 40
So, you see the number_id FROM save_subnumber is not equal to new inserted id FROM save_number. I would be appreaciated if anyone help me. By the way I am still using mysql_query. I can not find time to improve my SQL to PDO :)
Your first query can be changed to
INSERT INTO
save_number (number)
SELECT
number
FROM
number
This will save you using PHP to iterate through rows and will be faster. A lot.
Having this in mind your second query would be
INSERT INTO
save_subnumber (number_id, subnumber)
SELECT DISTINCT
sn.id, s.subnumber
FROM
saved_number AS sn
CROSS JOIN
number AS n
USING (number)
INNER JOIN
subnumber AS s
ON
n.id = s.number_id
If you just want to copy one table in another why don't you use something like this
INSERT INTO save_number SELECT * FROM number;

Select max win series: sql query

MySQL
I have table, where i store user_matches and it result:
n_match id_user id_score
1 55 1
1 66 0
This mean, 'user with id=55 win match with id=1 to user with id=66'.
So, we have 10, 100, 1000 matches, where user win or lose to opponents:
n_match id_user id_score
1 55 1 (win)
1 66 0
2 55 0 (lose)
2 77 1
3 55 1 (win)
3 77 0
4 55 1 (win)
4 77 0
5 55 1 (win)
5 77 0
Ok. As u can see, user win 3 matches without losing (win series)- and that's what i need from my query.
Question: How could i get from this table the longest series of won matches? Is it possible without looping on sql side or server side- just from query?
Thx.
Edit: One of solution i just now understand,- to get all matches as string like 001010101111010101011, then split it into array of strings with separator '0' -> [1, 1, 1, 1111, ...] and just take the longest string length.
But in this case i have to write server side code =\ That's not good, but mb the fastest.
The best way to do this is to calculate the cumulative number of losses for any match. For a sequence of wins, this value is constant. You can then use group by to get the length of the longest such sequence.
This version of the query is database-neutral. It uses subqueries to get the counts:
select user_id, max(NumWinsInRow)
from (select user_id, cumlosses, count(*)-1 as NumWinsInRow
from (select m.*,
(select sum(case when id_score = 0 then 1 else 0 end) from user_matches m2 where m2.id_user = m.id_user and m2.n_match <= m.n_match
) as CumLosses
from user_matches m
) t
group by cumlosses, user_id
) t
group by user_id
This query should run faster if you have an index on user_matches(id_user, n_math, id_score).

PHP MySQL: Take highest values from multiple categories and write an array?

I have a table of student scores. Students can take the test multiple times, we only care about the highest score.
So the table looks something like this:
UserID CatID Score
20 5 60
20 5 85
20 5 80
20 6 90
20 7 80
20 7 75
20 7 90
22 5 75
22 5 85
Want to get back one row based on a UserID variable that looks like this:
UserID Cat5 Cat6 Cat7
20 85 90 90
Here's what I'm using so far as a query:
SELECT score AS Score
, catid
FROM `quiz_result`
WHERE userid=65 and catid=5
ORDER BY score DESC
LIMIT 0, 1
Not sure how to get the other categories in one row...thoughts?
Thanks!
Try this piece:
SELECT catID, MAX( score ) FROM `quiz_result`
GROUP BY catID;
The output isn't exactly same as in your sample, but it pretty much gives what you need.
EDIT
Output will be like:
catID MAX(score)
Cat5 85
Cat6 90
Cat7 90
To get other columns, just include their names in the SELECT query.
Try this :
SELECT CONCAT_WS(',', catID) AS catID, CONCAT_WS(',', MAX(score)) FROM `quiz_result` GROUP BY catID;

Categories