Alright so i need to post the top 3 business categories with the top searches. I've tried the advice provided to be online:
$sql = "select search, city, business, count(*)
from vendor
group by category = 'Beauty Salon'
order by count(*) desc
fetch first 3 rows only";
I've tried:
$sql = "SELECT search, city, business,
COUNT(*) AS total FROM vendor
WHERE category = 'Beauty Salon' GROUP BY ASC LIMIT 3";
I've had others but to be honest I've tried it in so many ways i can't remember the sources.
I hope you can help me with this. Thank you!
Here is the full code i have been trying maybe it has nothing to do with the sql, but what comes afterwards.
<?php
include '../s.php';
$sql = "SELECT search, city, business, COUNT(*) AS total FROM vendor WHERE category = 'Beauty Salon' GROUP BY ASC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc())
{ ?>
<table class="demo">
<thead>
<tr class="titledemo" align="left">
<th width="25%">Ranking</th>
<th width="25%">Business</th>
<th width="25%">Searches</th>
<th width="25%">Category</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<? echo "<strong>" . $row["business"]. "<br></strong>";?>
</td>
<td>
<? echo "" . $row["search"]. "<br>";
?>
</td>
<td>
<? echo "" . $row["city"]. "<br>"; ?>
</td>
</tr>
</tbody>
</table>
<?
}
} else {
echo "0 results";
}
$conn->close();
?>
NOTE: when it did show before it would not align the rows from the top the least. It is showing 100, 200, 300 and not 300, 200, 100. I do believe that it is grabbing the top to lest by the date it was inserted because that is how the numbers are set in my database. I didn't understand since I've tried DESC and ASC and none showed what i needed. It should be based on search since that's the number amount of searches for each company.
You need a subquery first before limiting your results.
select * from (select search, city, business, count(*) ct
from vendor
where category = 'Beauty Salon'
group by search, city, business) t
order by ct asc
limit 3
Try this :
SELECT search, city, business,
COUNT(*) AS total FROM vendor
WHERE category = 'Beauty Salon' and ROWNUM <=3
try "TOP 3" after SELECT.
SELECT TOP 3 search, city, business
FROM vendor
GROUP BY category = 'Beauty Salon'
Related
I can count number of a table rows by using mysqli_num_rows. I have a table which contains similar rows. How can I count by grouping by similar row?
For instance: I have a table with 2 columns : Student and Option. Let say there are 50 students. 20 are in Economy option, 20 are in Management option and 10 are in Secretary Option. How can display those numbers. I can display only the 50.
my codes
$qry = "select * from table group by option";
$req= #mysqli_query($conn, $qry);
$result = mysqli_query( $conn, "select id from table");
$num_rows = mysqli_num_rows($result);
Students Total (<?php echo $num_rows ?>)
<table >
<tr>
<th>Student</th>
<th>Option</th>
</tr>
<?php
while($row=mysqli_fetch_array($req))
{
?>
<tr>
<td><?php echo $row['student'] ?></td>
<td><?php echo $row['option'] ?></td>
</tr>
<?php
}
?>
</table>
Here is the query you need:
SELECT COUNT(*) AS `option_count`, * -- returns a count aliased as "options_count"
FROM `table`
GROUP BY `option` -- will group the options and show the counts
Now you can echo the count, along with other data:
echo $row['count_options'];
echo $['options'];
The problem that you have here is that you will not be able to display each student in the option because this counts / groups only the three options.
Behold the proper query :
$qry = "select option as opt, COUNT(*) AS option from table group by option";
i have a question for the experts. I have no idea how to combine all the order ID with the same ID,
like in the picture, all orders with order ID = 1 are in one transaction, how do i combine all order IDs with the same id and display only one total price for all of the proudcts bought. and since all order ID are the same so the deliver and payment option will also be the same just need to display one row.
and a follow up question is how will i also show all the products bought if i combine all the same order IDs, compute the total price and display delivery and payment option in one single row
Here is the picture for my database relationship, i just followed the ones on the internet. the only difference is that "products" are changed to "inventory" and "serial" in products are changed to "prod_id"
here are my codes to display the current picture.
<?php
session_start();
$conn = #mysql_connect("localhost","root","");
$db = #mysql_select_db("");
$qry = "SELECT customers.name,customers.payment,customers.carrier, orders.date, order_detail.productid, order_detail.quantity, order_detail.price, order_detail.orderid, inventory.prod_name
FROM customers
RIGHT JOIN orders on customers.serial=orders.serial
RIGHT JOIN order_detail on orders.serial=order_detail.orderid
LEFT JOIN inventory on order_detail.productid=inventory.prod_id where customers.email='{$_SESSION['email']}'";
mysql_set_charset("UTF8");
$result = #mysql_query($qry);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
echo "<center>";
echo "<table class='CSSTableGenerator'>
<tr>
<td>Date of Purchase</td>
<td>First Name</td>
<td>Order ID</td>
<td>Products</td>
<td>Quantity</td>
<td>Total Price</td>
<td>Delivery Option</td>
<td>Payment Option</td>
<tr>";
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['date']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['orderid']."</td>";
echo "<td>".$row['prod_name']."</td>";
echo "<td>".$row['quantity']."</td>";
echo "<td>".($row['price']*$row['quantity'])."</td>";
echo "<td>".$row['carrier']."</td>";
echo "<td>".$row['payment']."</td>";
echo "</tr>";
}
echo "</table>";
?>
</table>
It seems that what you're needing to learn for this particular question is the SQL Group By clause.
This (untested, might need minor tweaking) should do the trick. Note that you don't get order item quantities out of this, but I would say that it's possible to get them.
SELECT o.date, c.name, o.serial as 'Order Id', GROUP_CONCAT(p.name) as 'Products', SUM(od.price) as 'Total', c.carrier, c.payment
FROM orders o
JOIN customers c on o.customer_id = c.serial
JOIN orderdetail od on o.serial = od.orderid
JOIN products p on od.productid = products.prod_id
GROUP BY o.serial
Of particular note is a handy aggregate function in MySQL called GROUP_CONCAT.
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
this is how I should use distinct to download the content again.
Here at pictures VISR it to the download content 3 times, but I only want it 1 time in total
what is the problem is that it does not pick all of them, but I only want it to pick up only one of time, which means that it only need to download one time by title and simultaneously username.
$sql = "SELECT DISTINCT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.title FROM fms_bruger INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id WHERE fms_opslagpm.til_id = ? ORDER BY fms_opslagpm.datotid DESC";
if ($stmt = $this->mysqli->prepare($sql)) {
$stmt->bind_param('i', $id);
$id = $_SESSION["id"];
$stmt->execute();
$stmt->bind_result($fornavn, $efternavn, $id, $title);
while ($stmt->fetch()) {
?>
<tr class="postbox">
<td class="beskedinfo">
<p><?php echo $fornavn . " " . $efternavn;?></p>
</td>
<td>
<?php echo $title;?>
</td>
<td>
Slet
</td>
</tr>
<?php
}
$stmt->close();
}
You need to use GROUP BY not DISTINCT to get the grouping of the title field.
SELECT fms_bruger.fornavn, fms_bruger.efternavn, fms_opslagpm.id, fms_opslagpm.title
FROM fms_bruger
INNER JOIN fms_opslagpm ON fms_bruger.id=fms_opslagpm.fra_id
WHERE fms_opslagpm.til_id = ?
GROUP BY fms_opslagpm.title
ORDER BY fms_opslagpm.datotid DESC
SELECT DISTINCT does exactly what it says: it selects distinct rows.
You include id in the columns. I'm pretty sure IDs will be unique, therefore all rows are DISTINCT.
Consider removing the DISTINCT keyword and adding a GROUP BY `fms_bruger`.`title` clause. This is an extension to the SQL standard which will return an arbitrary row for each unique title.
As a self-taught (poorly) PHP coder, I have exhausted all the trial-and-error possibilities so I humbly ask your help for a small problem I have been having while coding a community online "bidding" game.
I have two tables in my DB - one, called DCO_sponsors, listing a list of IDs, an associated amount of (virtual!) money, an availability counter and (if they are already associated with a team), the team's id.
Structure: id, amount, available, team_id
The second table, DCO_bids, lists the team's "bids" to clinch the above mentioned sponsors. It includes a bid id, the team id, a "part_b" which in this case is the sponsor id (the same table is used by other processes), a concept field where the kind of bid is described (e.g. "sponsorship") and finally two fields for the bid amount and the current status (A for active, W for waiting/pending, etc).
Structure: id, team_id, part_b, concept, bid, status
What I want to achieve is the site to show me (the admin) a list of all the sponsors in the DCO_sponsors table, ordered by the amount, and next to it the team_id of the team which bid the highest for it (teams only get four "sponsors" and get the highest grossing first, so it's important I see them in order of amount).
The code I produced, and that I hoped it would work, is as follows:
echo "<table>";
echo "<tr><th width=30>Id</th><th width=100>Amount</th><th width=220>Team</th><th width=100>Offer</th><th></th><th></th><th></th></tr>";
$data = mysql_query("SELECT id, amount FROM DCO_sponsors WHERE available='1' ORDER BY amount DESC", $CONNECTW);
while($row=mysql_fetch_row($data))
{
$sp_id = "$row[0]";
$sp_amount = number_format($row[1]);
$teamdata = mysql_query("SELECT team_id, bid FROM DCO_bids WHERE concept='sponsorship' AND part_b='$sp_id' ORDER BY bid DESC", $CONNECTW);
while($row=mysql_fetch_row($teamdata))
{
$team_id = "$row[0]";
$team_bid = number_format($row[1]);
}
// I call the name of the team from another table
$teamlabel = mysql_query("SELECT completename FROM DCO_teams WHERE id='$team_id'", $CONNECTW);
while($row=mysql_fetch_row($teamdata))
{
$teamname = "$row[0]";
}
echo "<tr><td>$sp_id</td><td>£$sp_amount</td><td>$teamname</td><td>$team_bid</td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A1&item_id=$item_id'><div id='IC_Tick' title='Sign Round 1 deal with $teamname'></div></a></td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A2&item_id=$item_id'><div id='IC_Tick' title='Sign Round 2 deal with $teamname'></div></a></td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A3&item_id=$item_id'><div id='IC_Tick' title='Sign Round 3 deal with $teamname'></div></a></td></tr>";
}
echo "</table>";
The links in the last cells of the row are tick-boxes linked to actions that modify other tables.
At the moment, the result I get is the list of the sponsors ordered by the amount (as it should be), but the team name appearing alongside it is the same for all rows, it's NOT the one of the highest bidder and the bid amount is NOT the one of the highest bidder but simply the first one to put one in.
I spent the best part of the last three nights trying to work out where I am getting this wrong... I hope you can help!
<table>
<tr>
<th width=30>Id</th>
<th width=100>Amount</th>
<th width=220>Team</th>
<th width=100>Offer</th>
<th></th>
<th></th>
<th></th>
</tr>
<? $data = mysql_query("SELECT id, amount FROM DCO_sponsors WHERE available='1' ORDER BY amount DESC", $CONNECTW); ?>
<? while($row=mysql_fetch_row($data)):
$sp_id = $row['id'];
$sp_amount = number_format($row['amount']);
$teamdata = mysql_query("SELECT team_id, bid FROM DCO_bids WHERE concept='sponsorship' AND part_b='$sp_id' ORDER BY bid DESC", $CONNECTW);
while($row=mysql_fetch_row($teamdata))
{
$team_id = $row['id'];
$team_bid = number_format($row['bid']);
}
$teamlabel = mysql_query("SELECT completename FROM DCO_teams WHERE id='$team_id'", $CONNECTW);
while($row=mysql_fetch_row($teamlabel))
{
$teamname = $row['completename'];
}
?>
<tr>
<td><?=$sp_id;?></td>
<td>£<?=$sp_amount;?></td>
<td><?=$teamname;?></td>
<td><?=$team_bid;?></td>
<td><a href='<?=$RKP;?>/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A1&item_id=<?=$item_id;?>'>
<div id='IC_Tick' title='Sign Round 1 deal with <?=$teamname;?>'></div></a></td>
<td><a href='<?=$RKP;?>/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A2&item_id=<?=$item_id;?>'>
<div id='IC_Tick' title='Sign Round 2 deal with <?=$teamname;?>'></div></a></td>
<td><a href='<?=$RKP;?>/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A3&item_id=<?=$item_id;?>'>
<div id='IC_Tick' title='Sign Round 3 deal with <?=$teamname;?>'></div></a></td>
</tr>
<? endwhile; ?>
</table>
Your issue came into play with your last while call. You were attempting to mysql_fetch_row($teamdata) again instead of $teamlabel.
Also, as a rule, you should just write out any html that doesn't need to be generated by php. So I broke that stuff out for you.
Fixed the problem - here is the code that works:
echo "<table>";
echo "<tr><th width=30>Id</th><th width=100>Amount</th><th width=220>Team</th><th width=100>Offer</th><th></th><th></th><th></th></tr>";
$query = mysql_query("SELECT id, amount FROM DCO_sponsors WHERE available = '1' ORDER BY amount DESC");
while($row = mysql_fetch_assoc($query)){
$sp_id = $row['id'];
$sp_amount = $row['amount'];
$sp_amount = number_format($sp_amount);
$tQuery = mysql_query("SELECT team_id, bid, id FROM DCO_bids WHERE concept='sponsorship' AND part_b='$sp_id' AND status='W' ORDER BY bid DESC");
$trow = ' ';
$trow = mysql_fetch_assoc($tQuery);
$team_id = $trow['team_id'];
$team_bid = $trow['bid'];
$team_bid = number_format($team_bid);
$item_id = $trow['id'];
$nquery = mysql_query("SELECT completename FROM DCO_teams WHERE id='$team_id'");
$nrow = mysql_fetch_assoc($nquery);
$teamname = $nrow['completename'];
echo "<tr><td>$sp_id</td><td>£$sp_amount</td><td>$teamname</td><td>£$team_bid</td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A1&item_id=$item_id'><div id='IC_Tick' title='Sign Round 1 deal with $teamname'></div></a></td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A2&item_id=$item_id'><div id='IC_Tick' title='Sign Round 2 deal with $teamname'></div></a></td><td><a href='$RKP/kernel/lib/php_lib/action/AC_Bids_Update.php?op=A3&item_id=$item_id'><div id='IC_Tick' title='Sign Round 3 deal with $teamname'></div></a></td></tr>";
}
echo "</table>";
I can't seem to find the right way to do this so I was hoping someone could give me some direction?
The SQL Database is structured like this (I've removed the irrelevant stuff):
Requests
R_ID R_FulfilledBy
1 Bob
2 Craig
3 Bob
SIMs
SM_ID SM_FulfilledBy
1 Bob
2 Craig
3 Bob
I'm hoping to end up with this output:
Fulfilled By Requests
Bob 4
Craig 2
Here's my PHP/HTML:
<div id="table">
<?php
//Connect to MySQL Database
$connection = mysql_connect($runnerdbServer, $runnerdbUser, $runnerdbPass);
mysql_select_db($runnerdbName, $connection) or die("MysQL Error");
$query = "SELECT R_FulfilledBy, COUNT(R_ID) FROM Requests GROUP BY R_FulfilledBy ORDER BY COUNT(R_ID) DESC";
$result = mysql_query($query) or die(mysql_error());
?>
<!-- Number of Runners (Counts total number of records in Requests table) -->
<table border='0' width='50%'>
<tr>
<th>Runners Fulfilled</th>
<tr><td><?php
$query = mysql_query("SELECT * FROM Requests");
$number=mysql_num_rows($query);
echo $number;
?>
</td></tr>
</table>
<!-- Fulfillment Stats -->
<table border='0' width='50%'>
<tr>
<th>Name</th>
<th>Runners Fulfilled</th>
</tr>
<?
// Print out result (I want this to calculate requests fulfilled by each user in 'Requests' and 'SIMs' table)
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td>". $row['R_FulfilledBy'] ."</td>";
echo "<td>". $row['COUNT(R_ID)'] ."</td>";
echo "</tr>";
}
?>
</table>
At present it's only calculating the records from the 'Requests' table :(
You could union all the two tables together in a subquery:
select FulfilledBy
, count(*)
from (
select R_FulfilledBy as FulfilledBy
from Requests
union all
select SM_FulfilledBy
from SIMs
) as SubQueryAlias
group by
FulfilledBy
Use union all instead of union because the second eliminates duplicates; which would give everyone a maximum count of 1.
I'd go with this:
SELECT R_FulfilledBy, COUNT(*) +
( SELECT COUNT(*) FROM SIMs WHERE R_FulfilledBy = SM_FulfilledBy )
FROM Requests GROUP BY R_FulfilledBy