i have a table where same data is appearing again and again the table structure is like below.id is autoincrement.pm is for userid.it will appear again and again like beliw table.i want to display the output as the extract of entire table in descending order. suppose the table consists of 100 rows and the userid 15 comes 10 times which is highest then it should come at the top then the other id which is coming next like that . i tried but not working here is my code as well
id userid
1 33
2 34
3 37
4 33
5 33
6 37
the output i want is
userid nos
33 3
37 2
34 1
please guide . i tried with this code
$res = sql_query("select count(userid) as total from tableA");
echo'<table>';
while ($row = sql_fetch_array($res)) {
echo ' <tr><td>'.$row['userid'].'</td></tr></table>';
You need to use a GROUP BY statement
SELECT userid, COUNT(userid) AS nos FROM tableA
GROUP BY userid ORDER BY nos DESC;
SELECT userid, COUNT(userid) FROM tableA AS nos GROUP BY userid ORDER BY nos DESC
Then you can access:
$row['userid'] for the user ID
$row['nos'] for the count
Your looping methodology is wrong.
$res = sql_query("select userid, count(userid) as total from tableA group by userid order by total desc");
echo'<table>';
while ($row = sql_fetch_array($res)) {
echo ' <tr><td>'.$row['userid'].'</td><td>'.$row['total'].'</td></tr>';
}
echo '</table>';
Related
I have the following record in my logtrama table:
id_logtrama fechaHora idCliente idEquipo
1 2021-04-18 20 8
2 2021-04-18 20 8
3 2021-04-18 20 8
4 2021-04-18 20 1
5 2021-04-18 4 4
And, in my equipo table the following:
idEquipo idCliente tipo
1 20 Alarm1
2 1 Alarm2
3 2 Alarm3
8 20 Alarm4
Now through my query I print results that match the given conditions:
$stmt = $con->prepare("SELECT l.id_logtrama,
l.fechaHora,
l.idCliente,
l.idEquipo,
l.statusGlobal
FROM logtrama l
INNER JOIN equipo e ON l.idEquipo=e.idEquipo AND l.idCliente=e.idCliente
WHERE DATE(fechaHora)=? GROUP BY l.id_logtrama");
$stmt->bind_param("s", $date_day);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result(
$id_logtrama,
$fechaHora,
$pag_idCliente,
$pag_idEquipo,
$statusGlobal
);
while ($stmt->fetch()) {
//print_r(expression)
}
}
In other words, it will print the following result:
1 2021-04-18 20 8
2 2021-04-18 20 8
3 2021-04-18 20 8
4 2021-04-18 20 1
Since it is the only data that matches the union of the two tables.
But now what I need is to be able to count the duplicate records in the same query in order to print data, in conclusion I want to achieve the following printing of the last data entered but with its respective count:
ID: 3 Date: 2021-04-18 ID Customer: 20 Id Team: 8 Total repeated records: (3)
ID: 4 Date: 2021-04-18 ID Customer: 20 ID team: 1 Total repeated records: (1)
How can I get that result? Could you explain to me what other conditions I can add to the query, perhaps COUNT (*) or SUM and how I would have to add this condition to obtain the desired result.
Thanks
I'm not entirely sure what you're trying to achieve but as far as I can tell you don't really need JOIN because your SELECT fields are all from one table. In the above it does limit the records to ones where there is an associated field in eqipo but I'm going to assume that you're just selecting on a per customer basis and thus will add a WHERE clause to that effect... If that isn't the case then you can simply add the INNER JOIN clause back in and remove the additional WHERE clause.
What you're attempting to do is aggregate fields together. You can do this in a couple of ways depending on your data and intentions.
From the looks of it all fields will be the same apart from the id_logtrama which means we can simply add them into the GROUP BY clause of your query:
GROUP BY idEquipo, fechaHora, idCliente
I'm assuming (from your example) that you want to also SELECT the highest id_logtrama? To do that we can utilise the MAX aggregate function:
SELECT MAX(id_logtrama) as id
Then of course you need to add in your WHERE and ORDER BY clauses, leaving you with something like:
SELECT MAX(id_logtrama) as id,
fechaHora as date,
idCliente as customer,
idEquipo as team,
COUNT(*) as count
FROM logtrama
WHERE fechaHora = ?
AND idCliente = ?
GROUP BY idEquipo, fechaHora, idCliente
ORDER BY id
In code:
$sql = "
SELECT MAX(id_logtrama) as id,
fechaHora as date,
idCliente as customer,
idEquipo as team,
COUNT(*) as count
FROM logtrama
WHERE fechaHora = ?
AND idCliente = ?
GROUP BY idEquipo, fechaHora, idCliente
ORDER BY id
";
$query = $con->prepare($sql);
$query->bind_param("si", $date_day, $client_id);
$query->execute();
$query->store_result();
$query->bind_result($id, $date, $customer, $team, $count);
while ($query->fetch()) {
echo "ID: {$id}, DATE: {$date}, CustomerID: {$customer}, TeamID: {$team}, Total: $count", PHP_EOL;
}
SELECT a.id_logtrama
, a.fechaHora
, a.idCliente
, a.idEquipo
, b.tipo
, c.totals
FROM logtrama a
JOIN equipo b
ON b.idequipo = a.idequipo
AND b.idCliente = a.idCliente
JOIN
( SELECT MAX(t.id_logtrama) id_logtrama
, COUNT(*) totals
FROM logtrama t
JOIN equipo e
ON e.idequipo = t.idequipo
AND e.idCliente = t.idCliente
GROUP
BY t.idcliente
, t.idequipo
) c
ON c.id_logtrama = a.id_logtrama;
...or something like that
Here I want to PF calculation, we are deducting pf for every month, now I want to display the total pf amount.this is my database table structure
id first_name pf_amount pf_month badge_number
1 Kani 200 01-2017 01
2 Mahesh 250 01-2017 02
3 Kani 200 02-2017 01
4 Mahesh 250 02-2017 02
In my list page I want to display badge_number (01) having 400 and badge_number (02) having 500. here badge_number is unique
I wrote the query like this but here I am getting all data, how can do bassed on my requirement
$check = mysql_query("SELECT * FROM pf_history");
while($row = mysql_fetch_array($check)) {
echo $row['pf_amount'];
}
Use GROUP BY AND SUM() in Query:
SELECT first_name, pf_month, SUM(pf_amount) as total FROM pf_history GROUP BY badge_number
Code:
$check = mysqli_query("SELECT first_name, pf_month, SUM(pf_amount) as total FROM pf_history GROUP BY badge_number");
while($row = mysqli_fetch_array($check)) {
echo $row['total'];
}
Reference for group by and sum():
GROUP BY
SUM()
You should use sum() and group by as follow:
SELECT first_name, pf_month, badge_number, SUM(pf_amount) as total_pf_amount
FROM pf_history
GROUP BY badge_number
PHP:
$check = mysql_query("SELECT first_name, pf_month, badge_number, SUM(pf_amount) as total_pf_amount
FROM pf_history
GROUP BY badge_number");
while($row = mysql_fetch_array($check)) {
echo $row['total_pf_amount'];
}
reference
My database structure looks somthing like below
customer_id product_id quantity
38 43 1
36 34 1
41 46 1
41 46 1
41 31 1
If the database has two product_ids with same value for the same customer_id then quantity have to be added and the rows must be combined to single row.
In the above case customer_id 41 has two product_id with value 46. So quantity of those two rows have to be added and two rows must be combined to single row.
I tried the below code, but it doesn't help me
$sql3 = "select customer_id,product_id from oc_cart where customer_id = '41'";
$products=mysql_query($sql3);
while($rows=mysql_fetch_array($products)){
$cust_id = $rows['customer_id'];
$prod_id = $rows['product_id'];
}
$sql4 = "select count(*) from oc_cart where customer_id =41 group by product_id ";
$count=mysql_query($sql4);
Any help would be really greatfull.
Thanks.
Need to use Mysql function SUM:
$sql4 = "select count(*), SUM(quantity) from oc_cart where customer_id =41 group by product_id ";
I have table in my data base which is storing the score of users table looks like this.
id user_id user_score
2748 371 3
2253 353 2
2254 353 2
2255 353 2
2256 353 2
2257 353 2
2258 353 2
2259 353 2
I want to calculate each users total score from this table and need to out put user name like this
user_id user_Score
357 x
367 y
354 z
Here x>y>z
Php code i am writing is something looks like this
<?php
//Expected query is contains user_id and user_query
$query="Expected query";
$connection=mysqli_connect("Connection varables");
$data=mysqli_query($connection,$query);
while($row=mysqli_fetch_array($data)){
echo "User name:";
echo $row['user_id'];
echo "</br>";
echo "Score:";
echo $row['user_score'];
echo "</br>";
}
?>
How to do this?.
SELECT user_id, MAX(user_score) as max_score
FROM your_table
GROUP BY user_id
ORDER BY max_score DESC
should be what you are looking for if I understood you correctly.
It gives you for each user the user's user_id as well as the user's highest score, sorted by the highscores.
Edit: If you are looking for the sum of all scores per user, this query will do the trick instead:
SELECT user_id, SUM(user_score) as score_sum
FROM your_table
GROUP BY user_id
ORDER BY score_sum DESC
Why this query instead of displaying the sum of points for each user, it display the sum of all together
I have written an SQL query that displays the sum of all point for all users, whereas I would like it to: display the sum of points for each user.
The table that I have written contains the following:
id | Score
1 | 20
2 | 30
2 | 50
1 | 10
Total table :
id | points
1 | 30
1 | 40
What I want is to add the score for user(1) = 30 and user(2) = 80
Id: 1 = 30 = Fail
Id: 2 = 80 = Pass
The query I have written :
$query = "SELECT SUM(sg.score) as sum, SUM(a.total) as suma FROM points as sg, totalpoints as a
WHERE a.id = 1 GROUP BY sg.id";
And related PHP code is as follows:
<?php
foreach($rowsum as $rowsm):
if( ' '. htmlentities($rowsm['sum']) . '' > 50 )
echo 'Pass';
else if( ' '. htmlentities($rowsm['sum']) . '' >= 40 )
echo 'Failed';
echo ' ' . htmlentities($rowsm['sum'], ENT_QUOTES, 'UTF-8') . '<br>';
endforeach;
?>
You need to group by the users ID:
SELECT SUM(score) as sum FROM points GROUP BY id ORDER BY id
You also have an incorrect WHERE clause
WHERE id=id
isn't needed.
I guess you should look forward using the GROUP BY clause :
SELECT
SUM(score) AS sum
FROM
points
GROUP BY
id
ORDER BY
id
You've omitted the GROUP BY clause:
$query = "SELECT SUM(score) as `sum` FROM points GROUP BY id ORDER BY id";
Your WHERE clause wasn't needed.
You need to do group by as below and it will give you the sum of scores for each user
SELECT SUM(score) as sum FROM points
group by id
ORDER BY id
If you need to find it for a specific user just add a where condition as
SELECT SUM(score) as sum FROM points
where id = 1
The above will give the sum of scores for id = 1 and can change for other values as needed.