Query to get top 5 users by total month sales amount - php

I was hoping you could help me figure this out. I would like to run a query that would search a table and all it's rows and the date matches the current month. Then return the user_id. What I am trying to achieve is gathering the top 5 user id's under this query.
How can I change this to find the top 5 for the current month? I am usually able to figure out my queries but this one has me stumped.
This is all I have at the moment.
$top = mysqli_query($mysqli, "SELECT sum(amount) AS total FROM sales WHERE status = 'S' AND MONTH(date) = 1");
while($row = mysqli_fetch_row($top))
{
$userid = $row['0'];
}
Update:
$top = mysqli_query($mysqli, "SELECT user_id
FROM
(
SELECT user_id, SUM(amount) total
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
) q
ORDER BY total DESC
LIMIT 5");
while($row = mysqli_fetch_row($top))
{
$topsales[] = $row['0'];
}
foreach($topsales as $topsale) {
echo $topsale;
}

Are you looking for a query like this?
SELECT user_id
FROM
(
SELECT user_id, SUM(amount) total
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
) q
ORDER BY total DESC
LIMIT 5
or just
SELECT user_id
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
ORDER BY SUM(amount) DESC
LIMIT 5
Here is SLQFiddle demo
Note: using MONTH() and YEAR() functions will prevent MySql from using any index you might have on date column
Now your php code might look like this
$db = new mysqli('localhost', 'user', 'password', 'dbname');
if ($db->connect_errno) {
die('Cannot connect'); // TODO: better error handling
}
$sql = "SELECT user_id
FROM sales
WHERE status = 'S'
AND MONTH(date) = MONTH(CURDATE())
AND YEAR(date) = YEAR(CURDATE())
GROUP BY user_id
ORDER BY SUM(amount) DESC
LIMIT 5";
$topsales = array();
if ($query = $db->prepare($sql)) {
$query->execute();
$query->bind_result($user_id);
while ($query->fetch()) {
$topsales[] = $user_id;
}
$query->close();
} else {
die('Unable to prepare: ' . $db->error); // TODO: better error handling
}
$db->close();
foreach ($topsales as $topsale) {
echo $topsale . '<br>';
}

Related

UNION doesn't work displaying error when combine with GROUP BY

I want to get the data by month so I can use it in my forecast/chart but the UNION doesn't seem to work well when combined with GROUP BY. Hope you can help me solve my problem.
$connect = mysqli_connect("localhost", "root", "", "testingfolder");
$query4 = "SELECT MONTHNAME(consultationstatus_date) AS MONTH,
consultationstatus_diagnosis,
count(*) as number
FROM tbl_consultationstatus
WHERE month(consultationstatus_date)=1
GROUP BY consultationstatus_diagnosis
ORDER BY number DESC LIMIT 1
UNION ALL
SELECT MONTHNAME(consultationstatus_date) AS MONTH,
consultationstatus_diagnosis,
count(*) as number
FROM tbl_consultationstatus
WHERE month(consultationstatus_date)=2
GROUP BY consultationstatus_diagnosis
ORDER BY number DESC LIMIT 1
";
$result4 = mysqli_query($connect, $query4);
while($row = mysqli_fetch_array($result4))
{
echo "['".$row["MONTH"]."', '".$row["number"]."','".$row["consultationstatus_diagnosis"]."'],";
}

Add COUNT and DISTINCT in $query

How to add select COUNT and DISTINCT in the below $query? Please let me know if you need any other details to solve this issue. Thank you for your time.
if(isset($_POST["intake_year"]))
{
$query = "
SELECT * FROM marketing_data
WHERE intake_year = '".$_POST["intake_year"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output[] = array(
'semester' => $row["semester"],
'student_matric' => floatval($row["count"])
);
}
echo json_encode($output);
}
//SELECT count(student_matric) AS count, semester, intake_year FROM marketing_data GROUP BY intake_year - This query is to only COUNT student_matric
//SELECT DISTINCT semester FROM marketing_data ORDER BY semester DESC - This query is to only DISTINCT semester
I guess you are looking for something like that
$query = "
SELECT distinct semester , count(student_matric) as count FROM marketing_data
WHERE intake_year = '".$_POST["intake_year"]."'
Group by student_matric " ;

group rows, count grouped rows and order by grouped rows

I want to make an analytics system for a website and I am trying to row accesed urls from a db, group by url, count grouped rows and order DESC by number of grouped rows.
$sql = "SELECT COUNT(*) FROM (SELECT DISTINCT url FROM analytic) ORDER by (SELECT DISTINCT url FROM analytic)";
$countQry = mysqli_query($link, $sql);
while($arr = mysqli_fetch_array($countQry)) {
?>
<?=$arr['url']?>
<?
}
?>
thanks
Try using a GROUP BY:
SELECT url, COUNT(url) AS theCount
FROM analytic
GROUP BY url
ORDER BY theCount DESC
Here is PHP code for you to use:
$sql = "SELECT url, COUNT(url) AS theCount FROM analytic GROUP BY url ORDER BY by theCount DESC";
$countQry = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($countQry, MYSQLI_ASSOC)) {
echo $row['url'], ", ", $row['theCount'];
}

SQL Select count of repeated dates

I'm trying to select count of repeated dates and output its numbers
$user_curr_id = $_SESSION['user_id'];
$sql = "SELECT COUNT(datum) FROM table_name WHERE user_ids = $user_curr_id";
I have no idea how to do it.
2014-07-23,2014-07-23,2014-07-23 => 3
2014-07-24,2014-07-24 =>2
2014-07-25 => 1
and get $result = 3,2,1
I assume you're looking after the GROUP BY clause:
$sql = "SELECT datum, COUNT(datum) as cnt
FROM table_name
WHERE user_ids = $user_curr_id
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
if your column datum is of the data type DATE.
Note
As already mentioned you're vulnerable to sql injection. You should use a parameterized prepared statement and bind your input value to this parameter like that:
$sql = "SELECT datum, COUNT(datum) cnt
FROM table_name
WHERE user_ids = ?
GROUP BY datum
ORDER BY COUNT(datum) DESC;";
$result = array();
if ($stmt = $mysqli->prepare($sql)) {
if ($stmt->bind_param('s', $user_curr_id)) {
if($res = $stmt->execute()) {
while ($row = $res->fetch_assoc()) {
$result[] = $row['cnt']; // add the content of field cnt
}
}
}
}
echo implode(',', $result);

How to use a Union properly with Order BY?

The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1

Categories