select top 5 sellers in mysql - php

I have the follow table in MySQL
TABLE "SALES"
id, product, code, quantity, amount, who-sold-it
while the field "who-sold-it" is just a example to understand the question but not the real name of the field
Now I have another table the name is "USERS" and it looks like this
id, name, sellercode
I need to get the top 5 sellers using the 2 tables looking the who-sold-it in each SALE and display their name and sold amounts

Order the results by total sales and take the top 5 with limit. You can also join the sales table with the seller table to get the name of the seller.
select users.name, users.sellercode, sum(sales.amount) as total
from sales, users
where sales.sellercode = users.sellercode
group by users.sellercode, users.name
order by total desc
limit 5
To display the result:
<?php while ($row = mysqli_fetch_assoc($result)) ?>
<tr>
<td><?php echo htmlspecialchars($row['name'])</td>
<td><?php echo htmlspecialchars($row['total'])</td>
</tr>
<?php } ?>

Related

Find 5 greatest totals after summing (quantity x value) for each qualifying user

I currently have a table which displays the inventory values of users. It works, but it displays all users and their inventory values in a random order. I'm wanting to limit the table to the top 5 descending inventory values only.
This data cuts across three tables: DB Fiddle
Users
Inventories (contains a row for each item a user has in their inventory)
Items (contains the value of the items)
echo "<table>
<th>Inventory Value</th>
<th>Username</th>";
// Choose the users we want (verified users).
$refineUsers=$db->query("SELECT userID FROM users WHERE accountVerified = 'true'");
while($users=$db->fetch_row($refineUsers)) {
// Fetch the inventories of the users we want.
$fetchInventories=$db->query("SELECT * FROM inventories WHERE userID = '".$users['userID']."'");
$totalInventoryValue=0;
while($inventories=$db->fetch_row($fetchInventories)) {
// Fetch the values of the items.
$fetchItemsData=$db->query("SELECT value FROM items WHERE itemID = '".$inventories['itemID']."'");
while($items=$db->fetch_row($fetchItemsData)) {
// Calculate the values of the various items within the user's inventory.
$totalItemsValue=($items['value'] * $inventories['quantity']);
// Calculate the total value of the user's inventory.
$totalInventoryValue+=$totalItemsValue;
}
}
// Display the values of each user's inventory.
echo "<td>".money_format($totalInventoryValue)."</td>";
echo "<td>".username($users['userID'])."</td>";
echo "<tr>";
}
echo "</table>";
The output is something like:
Inventory Value
Username
120000
Account1
112000
Accounts2
70000
Account3
169000
Accounts5
I'm guessing this could be done with a JOIN query, but I'm not very experienced and haven't done one that cuts across three tables before. I don't know how I can use these nested queries to get the top 5 inventory totals and arrange them in descending order.
Join the three table is accordance with the rules in your original nested queries.
Group the data on username values.
This will create AGGREGATE data which will need to be organized within the SUM() function so that the item quantities associate with the correct item value.
Now it is trivial to apply your ORDER BY and LIMIT rules.
SQL: (Demo)
SELECT username,
SUM(
IF(
inventoryItemID = itemID,
inventoryQuantity * itemValue,
0
)
) AS total
FROM users
JOIN inventory ON userID = inventoryUserID
JOIN items ON inventoryItemID = itemID
WHERE accountVerified = 'true'
GROUP BY username
ORDER BY total DESC
LIMIT 5

How to group database tables using Group By

I am developing a simple php shopping cart site which connected to a databse named products and has tables Orders,user,products. The orders table has the following fields :
OrderId , product_id , user_id , quantity ... When the user orders for example 3 products . The data is inserted from SESSION['cart'] Below is the query
$query = "insert into orders (product_id,user_id,Quantity) values ('$key','$id','$value')";
mysql_query($query);
Now the problem is if user orders more than one product, three orderID's are generated, because he ordered 3 products and each orderId refers to that product. When i use the select statement it shows all the orders of the users but i want to group them, So that if person ordered more than 1 products at a time, the list would show me single orderID but all the products with the user who ordered it. Below is the image of database table record from orders table and the select query i am using ..
OrderId product_id user_id Quantity
1 4 1 1
3 21 1 3
4 19 1 1
5 21 1 3
6 19 1 2
$sql1=mysql_query("SELECT * FROM orders,USER WHERE user.`user_id`=orders.`user_id`");
while($row = mysql_fetch_array($sql1))
{
$sReturn .='
<tr>
<td>' . $row['user_id'] . '</td>
<td>' . $row['OrderId'] . '</td>
<td>' . $row['product_id'] . '</td>
<td>' . $row['Quantity'] . '</td>
</tr>';
}
What select query can be used someone told me groupby with sum ..
this will get u the sum of products by each user according to product_id
Updated
SELECT SUM( orders.Quantity ) , COUNT( orders.order_id ) , orders.user_id
FROM orders join user on (user.`user_id`=orders.`user_id`)
GROUP BY orders.user_id
You need to add a table called something like OrderItem or OrderRow where you put the product information for each order. Fields could be OrderID, ProductID, Quantity, ItemPrice.
It's a good idea to store the price you told the customer at the time of ordering, otherwise you will get a lot of problems when changing prices in the future.
You need to fix your order_id - it cant be autoincrement. Then this is what I think you are asking.
select order_id, sum(quantity)
from orders
group by order_id
I have left the where clause out as I dont know what filter you will want on it.
SELECT * FROM user_table WHERE id =
(SELECT user_id FROM order_table WHERE order_id = n limit 1);
But much better if you will create separate table for order which containing order info and table for linking an order and a products (id, order_id, product_id, quantity).
I have figured out the query .. below is the query for getting number of orders + Quantity or Number OF Products + user_id ...
SELECT user.`user_id`,SUM(quantity) AS Number_Of_Products,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN USER
ON Orders.user_id=user.`user_id`
GROUP BY username;
below is the output
user_id Number_Of_Products NumberOfOrders
1 10 5

php mysql view total amount from the database

I want to echo sum of Amound row with student id but I have another column which is call "type" (it should be have only Admission, Installment, Other).
so when I want to echo it should be show the total of the amount column but not included (Other from "Type")
I want to echo that red box total with particulate student id
select sum(Amount) as total_amount
from `table_name`
where `Type` in('Admission', 'Installment', 'Other') group by Student_ID

Mysql count with descending with join and where clause ,two tables, limit?

Here i have implemented two tables (pages, pagestatistics).I need result for last five records using join from the those tables and also i need a count of cID field from second table (pagestatistics), i need that count result will be display in descending.
NOTE : Primary id is cID.
![pagestatistics][1]![pages][2]
<?php
$recentpageviews =mysql_query("SELECT Distinct(cID) FROM `pagestatistics` order by `pstID` desc limit 0,5");
$downloads=mysql_num_rows($recentpageviews);
$k=1;
$cid="";
while($views_values=mysql_fetch_array($recentpageviews))
{
$cid.=",".$views_values['cID'];
$k++;}
}
$explode =explode(",",$cid);
for($i=1;$i<count($explode);$i++)
{
$sql=mysql_query("select Distinct(a.cID),count(a.cID) as clicks,b.cFilename,a.date from pagestatistics as a left join pages as b on a.cID=b.cID where a.cID='".$explode[$i]."' order by a.cID desc");
$res=mysql_fetch_array($sql);
?>
<tr>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['cFilename'];?></td>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['clicks'];?></td>
<td class='ccm-site-statistics-downloads-title'><?php echo $res['date'];?></td>
</tr>
<?php }?>
How to display all records in descending order.
Thank in advance.
You can do it in this way just order by with your count separated with , in ORDER BY clause
$sql=mysql_query("select Distinct(a.cID),count(a.cID) as clicks,b.cFilename,a.date
from pagestatistics as a left join pages as b on a.cID=b.cID
where a.cID='".$explode[$i]."' order by a.cID,clicks desc");

output results from 2 mySQLtables

I have 2 tables in my mySQL database csm and csmproducts.
Table csm stores the customer info and table csmproducts stores the products they ordered.
"Order_ID" is the common variable in both tables.
I have written a query which pulls data from both tables.
My query looks like this:
$query = "SELECT c.*, p.Product_SKU from csm c, csmproducts p where c.Order_ID = p.Order_ID and c.Order_Status='Awaiting Fulfillment' group by Order_ID order by Order_ID DESC LIMIT $startrow, 50";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
}
The trouble I am having is that if one order (hence one Order_ID) has multiple products in it , only the first product is showing.
What do I need to do so that where {$row['Product_SKU']} gives me only the first product for a particular Order_ID, that I am able to pull all the Product_SKUs for that particular Order_ID?
For example Order_ID 5558 has 3 products associated with it (DSC-3433, ASD-6454, UFY-7383)
Currently the output looks like this (showing just the first item the customer orderd)
Order ID: 5558
Product SKU: DSC3433
I would like to see it like this:
Order ID: 5558
Product SKU: DSC-3433, ASD-6454, UFY-7383
That is: all 3 products associated with that Order_ID to be shown.
Thanks in advance for the assistance.
USE GROUP_CONCAT
with exlplanation

Categories