I should compare students by month - mysql

public function getComparisonStudentsByMonth()
{
$last_month = date('m', strtotime('-2 month'));
$previus_month = date('m', strtotime('-1 month'));
return
$this->db->select('MONTH('student_add_date')', date('m'));
$this->db->where('student_add_date <= DATE_ADD(NOW(),INTERVAL 30 DAYS)');
$query = $this->db->get('students')->result();
}
Problem
User every month inserting new students and admin page should show the comparison in percentage between months. I should take last month like 100% and compare with current month. I understand the logic but how to do with MySql.

To get all percentage of every month you can use this:
SELECT (MONTH(student_add_date)) AS month_temp, ((count(*) /(SELECT count(*) FROM students)) * 100)percentage from students group by month_temp
to get between two month you need to specify month in query. for example i will search in september(9) and oktober(10)
SELECT
(MONTH(student_add_date)) AS month_temp,
((count(*) /(SELECT count(*) FROM students WHERE MONTH(student_add_date) = 9 OR MONTH(student_add_date) = 10)) * 100)percentace
from students
WHERE
MONTH(student_add_date) = 9
OR
MONTH(student_add_date) = 10
group by month_temp
In codeigniter you can run custom query like this:
$query = $this->db->query('SELECT
(MONTH(student_add_date)) AS month_temp,
((count(*) /(SELECT count(*) FROM students WHERE MONTH(student_add_date) = 9 OR MONTH(student_add_date) = 10)) * 100)percentace
from students
WHERE
MONTH(student_add_date) = 9
OR
MONTH(student_add_date) = 10
group by month_temp');
$result = $query->result_array();
// var_dump($result);
return $result;

public function getComparisonStudentsByMonth()
{
$last_month = date('m', strtotime('-2 month'));
$previus_month = date('m', strtotime('-1 month'));
$last_month = $this->db->where('MONTH(student_add_date)', $last_month)
->count_all_results('students');
$previus_month = $this->db->where('MONTH(student_add_date)', $previus_month)
->count_all_results('students');
$result = $previus_month * 100 / $last_month;
return $result;
}

Related

I have a mysql query where I am trying to add a count and a WHERE clause at the same time

I have a query where I am trying to add a count and WHERE clause at the same time. I cannot figure it out at all. Any help on this would be greatly appreciated! My code(With the erroneous code commented out) is below:
SELECT
RegDate,
DATE_FORMAT(RegDate,'%M') AS RegMonth,
DATE_FORMAT(RegDate,'%Y-%m') AS RegMonthNum,
DATE_FORMAT(RegDate,'%M, %Y') AS RegMonthYear,
DATE_FORMAT(RegDate,'%d') AS RegDay,
YEAR(RegDate) AS RegYear,
#COUNT(SELECT * FROM Registration WHERE LMSCID = 14) AS Florida,
#COUNT(SELECT * FROM Registration WHERE LMSCID = 2) AS New England,
#COUNT(SELECT * FROM Registration WHERE LMSCID = 32) AS Colorado,
COUNT(SwimmerID) AS NumberOfSwimmers,
CASE
WHEN LastYearRegistered = 2018 THEN 'Renewal'
WHEN LastYearRegistered IS NULL THEN 'New'
ELSE 'Return'
END AS MemberStatus
FROM
(SELECT
Reg_NewYear.SwimmerID,
Reg_NewYear.RegDate,
MAX(Registration.Year) AS LastYearRegistered
FROM
(SELECT DISTINCT
SwimmerID,
RegDate
FROM
Registration
WHERE
Year = 2018
AND TransferredOut = 0
) AS Reg_NewYear
LEFT JOIN Registration
ON Reg_NewYear.SwimmerID = Registration.SwimmerID
AND Registration.Year < 2018
GROUP BY
Reg_NewYear.SwimmerID
ORDER BY
LastYearRegistered) AS SwimmersAndYears
GROUP BY
RegDate,
MemberStatus
ORDER BY
RegDate,
LastYearRegistered DESC
Instead of this:
COUNT(SELECT * FROM Registration WHERE LMSCID = 14) AS Florida,
Use this:
(SELECT COUNT(*) FROM Registration WHERE LMSCID = 14) AS Florida,

Convert this sql code to codeigniter?

How do i convert this sql code to CodeIgniter?
SELECT *,sum(sales_total) as daily_report FROM `tbl_sales`,(select
sum(sales_total) as month from tbl_sales where date_format(sales_date,'%m') = '01') as totals where sales_date = '2018-01-18'
$sub_query_from = "tbl_sales,(SELECT SUM(sales_total) AS month FROM tbl_sales WHERE date_format(sales_date,'%m') = '01') AS totals";
$this->db->select('*, SUM(sales_total) AS daily_report');
$this->db->from($sub_query_from);
$this->db->where('sales_date','2018-01-18');
$query = $this->db->get();

MYSQLi and Highcharts

I am having trouble with my MYSQL query. I can send it to Highcharts but is is not quite right.
I want to get last months temperature and put it in Highcharts.
My query sort of works but only gets the first temperature for each day, and that is just after midnight. How do I make a query that will get hourly temperatures daily for a month?
This is my query. I am sorry I cannot get this formatting correct.
<?php
$con = mysqli_connect("localhost","root","root","manortsc_test");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
$sth = mysqli_query($con,"
SELECT DateTime,T
FROM alldata
WHERE YEAR(DateTime) = YEAR(CURDATE()) AND MONTH(DateTime) = MONTH(CURDATE() - INTERVAL 1 MONTH)
GROUP BY YEAR(DateTime), MONTH(DateTime), DAY(DateTime)
"
);
$rows = array();
$rows['name'] = 'Outside';
while($r = mysqli_fetch_array($sth)) {
$rows['data'][] = $r['T'];
}
$sth = mysqli_query($con,"
SELECT DateTime,Ti
FROM alldata
WHERE YEAR(DateTime) = YEAR(CURDATE()) AND MONTH(DateTime) = MONTH(CURDATE() - INTERVAL 1 MONTH)
GROUP BY YEAR(DateTime), MONTH(DateTime), DAY(DateTime)
"
);
$rows1 = array();
$rows1['name'] = 'Inside';
while($rr = mysqli_fetch_assoc($sth)) {
$rows1['data'][] = $rr['Ti'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Spent all night researching and came up with the answer.
It simply gets the maximum T each day for the month. I can build on this.
Hope it helps someone.
SELECT DateTime,max(T)
FROM alldata
WHERE YEAR(DateTime) = YEAR(CURDATE()) AND MONTH(DateTime) = MONTH(CURDATE() - INTERVAL 1 MONTH)
GROUP BY day(DateTime)
"

mysql query returning different dates

I am trying to add a new feature to my weather station, date of highest temperature and the date it rained the most.
Why do does this code give different dates in the result?
If I changed the first query to either T, R, P or H, the maximum for the row are shown but the date is always the same.
Once I understand that, I may be able to fix other problems with the code.
This is the output
$result = mysqli_query($con,"
SELECT DateTime,max(Tmax)
FROM alldata
WHERE YEAR(DateTime) = YEAR(NOW())
"
);
while($row = mysqli_fetch_array($result)){
$maxtempDate1 = $row['DateTime'];
$tempMax1 = $row['max(Tmax)'];
}
$result = mysqli_query($con,"
SELECT DateTime,Tmax
FROM alldata
WHERE Tmax=(select max(Tmax) from alldata)
AND YEAR(DateTime) = YEAR(NOW())
"
);
while($row = mysqli_fetch_array($result)){
$maxtempDate = $row['DateTime'];
$tempMax = $row['Tmax'];
}
$result = mysqli_query($con,"
SELECT DateTime,Tmax
FROM alldata
WHERE YEAR(DateTime) = YEAR(NOW())
ORDER BY Tmax DESC
LIMIT 1
"
);
while($row = mysqli_fetch_array($result)){
$maxtempDate = $row['DateTime'];
$tempMax = $row['Tmax'];
}

Laravel Join table and query

I have 3 table. Users, Accounts and Booking. I have try three table join and year and month wise query. [3 Table diagram][1]
But query booking calculation is show wrong. It's showing double quantity.
$january = DB::table('users')
->join('bookings', 'users.id', '=', 'bookings.user_id')
->join('accounts', 'users.id', '=', 'accounts.user_id')
->orderBy('users.room_id','asc')
->groupBy('users.id')
->whereYear('bookings.bookingdate','=', '2016')
->whereMonth('bookings.bookingdate','=','01')
->whereYear('accounts.accountdate','=', '2016')
->whereMonth('accounts.accountdate','=','01')
->select('users.*',
DB::raw("COUNT(case when bookings.breakfast='on' then 1 else null end) AS t_breakfast"),
DB::raw("COUNT(case when bookings.lunch='on' then 1 else null end) AS t_lunch"),
DB::raw("COUNT(case when bookings.dinner='on' then 1 else null end) AS t_dinner"),
DB::raw("SUM(accounts.amount) AS t_amount")
)
->get();
dd($january);
My Accounts table is:
Accounts Table
My Booking table is:
Bookings Table
When I'm run this query it's show:
+"t_breakfast": "2"
+"t_lunch": "2"
+"t_dinner": "2"
+"t_amount": "22.00"
But I need t_breakfast, t_lunch, t_dinner quantity is: 1. But It's showing double.
When I try one query I did not solved this problem. then I try two query and solved it.
$data = DB::select("SELECT users.id, users.name , users.picture, users.room_id,
SUM(CASE WHEN bookings.breakfast='on' THEN 1 ELSE 0 END) AS t_b ,
SUM(CASE WHEN bookings.lunch='on' THEN 1 ELSE 0 END) AS t_l ,
SUM(CASE WHEN bookings.dinner='on' THEN 1 ELSE 0 END) AS t_d FROM `users`
INNER JOIN
`bookings` ON users.id=bookings.user_id AND
MONTH(bookings.bookingdate) = $month AND
YEAR(bookings.bookingdate) = $year
GROUP BY users.id
ORDER BY users.room_id ASC");
$datas = [];
$data = json_decode(json_encode($data),true);
foreach ($data as $key => $value) {
$x = [];
$x = $value;
$x['exp'] = Account::where('user_id',$x['id'])->whereMonth('accountdate','=',$month)->whereYear('accountdate','=',$year)->sum('amount');
$datas[] = $x;
}
$total_t_b = $total_t_l = $total_t_d = $total_exp = 0;
foreach ($datas as $data) {
$total_t_b += $data['t_b'];
$total_t_l += $data['t_l'];
$total_t_d += $data['t_d'];
$total_exp += $data['exp'];
}
$g_total = $total_t_b + $total_t_l + $total_t_d;
if($g_total <= 0) {
$perbookingprice = 0;
} else {
$perbookingprice = $total_exp / $g_total;
}