Grouping records from MySql - php

I've got two tables in MySql
1 (Staff): Id/Name/SecondName
2 (fee):
Id/StaffId/Date(yyyy-mm-dd)/HoursWorked(hh:mm)/fee(int)/workType
There is also a script adding records to fee table.
I'm trying to group data in php to create html table like:
Name, Second Name | January 2009 | 123:45 hours | 2100,00 USD
February 2009...
March 2009 ....
Next person... etc.
So generally I'm trying to sum fee and hours in specific month and print a report from database...
And I need some advice/help... What is the bast way to create table like this?

Maybe something like this? Not tested though...
SELECT s.Name, s.SecondName, CONCAT(DAYOFMONTH(f.Date),', ',YEAR(f.Date)),
SUM (f.HoursWorked), SUM(f.Fee)
FROM Staff s
JOIN Fee f ON f.StaffId = s.Id
GROUP BY s.Id, YEAR(f.Date), MONTH(f.Date)
Edit: Ofcourse you need to group on s.Id...

That's not the best way, but if you want to do it with one query (it's easy to export to Excel):
SELECT
s.Name,
s.SecondName,
DATE_FORMAT('%M %y', f.`Date`),
SEC_TO_TIME( SUM( TIME_TO_SEC( `HoursWorked` ) ) ) as TotalHours,
sum(fee) AS TotalFee
FROM
Staff AS s
INNER JOIN fee AS f on s.id = f.StaffId
WHERE
1
GROUP BY s.id, YEAR(f.`Date`), MONTH(f.`Date`)
You cal also query stuff:
// that's not a real function, just get all Staff into $staff
$staff = QueryRows(SELECT * FROM Staff);
and then query fee:
foreach($staff as $s){
// use this query to query statistics
SELECT * FROM fee
WHERE StaffId = $s['id']
GROUP BY StaffId, YEAR(f.`Date`), MONTH(f.`Date`)
}

I'm not 100% sure about this being perfect but it should definitely point you in the right direction. The AVG() function calls might be unnecessary.
SELECT
Name,
SecondName,
SUM(fee.HoursWorked) as HoursWorked,
SUM(fee.fee) as fee,
YEAR(AVG(fee.Date)) as year,
MONTH(AVG(fee.Date)) as month
FROM Staff
JOIN fee ON staff.id = fee.staffid
ORDER BY fee.Date
GROUP BY staff.id, YEAR(fee.Date), MONTH(fee.Date)

Related

Sum columns on different tables and multiply by value of a column on another table

I need to compute employees' monthly salaries based on meetings attended, deductions and bonuses given;
Employees have different pay per meeting based on their job position.
The solution is:
salary = (Pay_per_minute * meetings_attended) + bonuses - deductions ;
I have four tables:
Jobs: Id, title, pay_per_meeting
Employees: Id, Name, job_id
Bonuses: Id, amount, employee_id, date
Deductions: Id, amount, employee_id, date
Meetings: Id, employee_id, date
SELECT
COUNT(meetings.employee_id) as meetings_attended,
COUNT(deductions.amount) as debt,
COUNT(bonuses.amount) bonus,
(SELECT jobs.pay_per_attendance from jobs where jobs.id = (select job_id from employees where id=meetings.employee_id)) as pay,
((meetings_attended * pay) + bonus - debt) as salary
FROM meetings
JOIN deductions ON deductions.employee_id = meetings.employee_id
JOIN bonuses ON bonuses.employee_id = meetings.employee_id
WHERE meetings.employee_id = 1
GROUP BY MONTH(meetings.date), MONTH(deductions.date), MONTH(bonuses.date)
The above query returns many incorrect values whenever i remove the salary line but gives error of unknown column pay, meetings_attended, debt and bonus, am sure something is wrong with the grouping but i can't just see it.
You can't refer to column aliases in the same select list as they're defined, you need to refer to the underlying column. And a subquery can't access an aggregate calculated in the main query. You need to repeat the aggregate expression, or move everything into a subquery and do the calculation with it in an outer query.
Also, all your COUNT() expressions are going to return the same thing, since they're just counting rows (I assume none of the values can be NULL). You probably want COUNT(DISTINCT <column>) to get different counts, and you need to use a column that's unique, so they should be the primary key column, e.g. COUNT(DISTINCT deductions.id).
Another problem is that when you try to sum and count values when you have multiple joins, you end up with a result that's too high, because rows get duplicated in the cross product of all the tables. See Join tables with SUM issue in MYSQL. The solution is to calculate the sums from each table in subqueries.
SELECT m.month, m.meetings_attended, d.debt, b.bonus,
m.meetings_attended * j.pay_per_meeting + b.amount - d.amount AS salary
FROM (
SELECT MONTH(date) AS month, COUNT(*) AS meetings_attended
FROM meetings
WHERE employee_id = 1
GROUP BY month) AS m
JOIN (
SELECT MONTH(date) AS month, COUNT(*) AS bonus, SUM(amount) AS amount
FROM bonuses
WHERE employee_id = 1
GROUP BY month) AS b ON m.month = b.month
JOIN (
SELECT MONTH(date) AS month, COUNT(*) AS debt, SUM(amount) AS amount
FROM deductions
WHERE employee_id = 1
GROUP BY month) AS d ON m.month = d.month
CROSS JOIN employees AS e
JOIN jobs AS j ON j.id = e.job_id
WHERE e.employee_id = 1

combine two tables and sum mysql

i want to join two tables but i can't do it as i want to sum column and get the result between two dates
first table named : vip_allotment_details
allotment_id qty
2 3
2 5
1 2
1 4
the second table name : vip_allotment
id date_from date_to
1 2017-10-1 2017-10-5
2 2017-10-6 2017-10-10
what i want from the query to get me this result
id qty date_from date_to
1 6 2017-10-1 2017-10-5
2 8 2017-10-6 2017-10-10
i will explain the result :
first allotment_id field is linked with id field in second table , the result i want that we can make sum of qty by the two fields (id , allotment_id ) between the date_from and date_to
and here is my try :
$query1 = "
SELECT SUM(qyt) as total
FROM vip_allotment_details
where allotment_id IN ( SELECT id from vip_allotment where date_from >= '$date_1' AND date_to <= '$date_2')
";
In my query the result gets all the sum of qty field with no filter ..
I hope I have explained my problem well .
thanks/.
I'm not try yet, but maybe you can try like this:
SELECT a.id AS id, SUM(qyt) AS qty, date_from, date_to
FROM vip_allotment AS a
LEFT JOIN vip_allotment_details AS b on b.allotment_id = a.id
WHERE a.date_from >= '{thedatestart}' AND a.date_to <= '{thedateend}'
GROUP BY a.id
ORDER BY a.id ASC;
You need to use JOIN. I see you are using IN keyword, which won't work. There can be many ways to solve your problem. One of them is,
select allotment_id, qty, date_from, date_to
from
(select allotment_id, SUM(qty) as qty
from vip_allotment_details group by allotment_id
) at
INNER JOIN
vip_allotment va
ON va.id= at.allotment_id;
I think the following should do what you ask.
SELECT
va.id,
SUM(vad.qyt) AS total,
va.date_from,
va.date_to
FROM vip_allotment_details AS vad
LEFT JOIN vip_allotment AS va ON va.id = vad.allotment_id
GROUP BY vad.allotment_id
Try below.i think you will get your desired result.
select va.id, temp.qty , va.date_from,va.date_to from vip_allotment as va
inner join (select sum(qty) as qty , allotment_id from vip_allotment_details group by `allotment_id`) as temp
ON temp.allotment_id=va.id
where va.date_from >= '$date_1' AND va.date_to <= '$date_2';
If you want more then one result form an aggregate function (SUM, COUNT, AVG, ...) you'll need to use a GROUP BY. Your query isn't that hard, this should do the trick:
SELECT va.id, va.date_from, va.date_to, SUM(vad.qyt) AS qyt
FROM vip_allotment AS va
LEFT JOIN vip_allotment_details AS vad ON vad.allotment_id = va.id
GROUP BY va.id
And as you can see here, this produces the expected result: http://sqlfiddle.com/#!9/707a8/2
If you now want to start adding extra filters (like filter by date), you can just do so by adding a WHERE to the query. Something like this:
...
LEFT JOIN ...
WHERE va.date_from >= "2017-10-06" and va.date_to <= "2018-10-06"
GROUP BY ...
http://sqlfiddle.com/#!9/707a8/6
On a side note, I noticed you are not binding your params in the php part of your code . Do note that this can pose serious security issues, especially if these dates come directly from the user input. I would suggest looking in to PDO to do the actual querying in PHP.
Try this..change your table name and run the query..hopefully it should give the result as your requirement..if not let me know...
select a.id
, sum(b.qty)
, a.date_from
, a.date_to
from table1 a
, table2 b
where a.id = b.allotment_id
group
by b.allotment_id

MySQL Need to show 0 when no value in right hand table of join, with cumulative

I have one table with a list of number of sales per month against product code and another with a list of months that can extend before or after the months that had a sale in. I need to results to show 0 sales if there were no sales in the month and for the cumulative to add this up. I have tried using case and if and getting it to put 0 if sales.sales was null but this did not work and I still just had blanks.
create table summary as (SELECT
q1.productid As productid,
q1.date AS Month_View,
q1.sales AS Monthly_Units_Sold,
(#runtot_sales := #runtot_sales + q1.sales) AS Cumulative_Sales
FROM
(SELECT
sales.productid,
dates.date,
if(sales.date is null,0,sales.sales) as sales
from
dates
left join sales on dates.date = sales.date
where
sales.productid = '$input1'
group by dates.date
ORDER BY date) AS q1);
";
Try COALESCE() function to return the first non-NULL value of a list Also see demo here
CREATE TABLE summary AS
(SELECT
q1.productid AS productid,
q1.date AS Month_View,
q1.sales AS Monthly_Units_Sold,
(
#runtot_sales := #runtot_sales + q1.sales
) AS Cumulative_Sales
FROM
(SELECT
sales.productid,
dates.date,
COALESCE(sales.sales, 0) AS sales
FROM
dates
LEFT JOIN sales
ON dates.date = sales.date
WHERE sales.productid = '$input1'
GROUP BY dates.date
ORDER BY DATE) AS q1) ;
MySQL COALESCE() function
You are misusing GROUP BY and therefore getting indeterminate results. See this: http://dev.mysql.com/doc/refman/5.5/en/group-by-extensions.html
If you're aggregating your items by product and date you probably want something like this.
SELECT sales.productid,
dates.date,
SUM(sales.sales) as sales
FROM dates
LEFT JOIN sales ON dates.date = sales.date
WHERE sales.productid = '$input1'
GROUP BY sales.productid, dates.date
ORDER BY /* i'm not sure what you're trying to do with the running total */
Note that SUM(sales.sales) handles the NULL values from your LEFT JOIN correctly. If the date doesn't join a sales row then sales.sales will be NULL.
If you're trying to do a month-by-month summary you need more logic than you have. See this writeup: http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Assistance with Search MySql DB using date and time range

I have a search page for my users and one of the things I want them to be able to do is search items in our DB using a time range.
Currently, my query looks like this:
select ****
from ****
where created_on >='{$errTimeDayOne}' and created_on <= '{$errTimeDayTwo}'
So, say $errTimeDayOne = 2013-03-24 00:00:00 and $errTimeDayTwo = 2013-04-01 01:00:00 it will search between that range. I'm trying to search between 00:00:00 - 01:00:00 through dates 2013-03-24 - 2013-04-01. Any thoughts or suggestions?
Update:
My query now looks like this:
SELECT call_id, priority_name, caller_name,
cust_name, cust_rep, caller_dept,
DATE_FORMAT(created_on , '%Y-%m-%d') AS created_on,
DATE_FORMAT(updated_on, '%Y-%m-%d') AS updated_on,
source_name, created_by, cat_name, subcat_name
FROM calls INNER JOIN categories ON calls.cat_id =
categories.cat_id INNER JOIN ticket_priority ON
calls.ticket_priority = ticket_priority.priority_id
INNER JOIN ticket_source ON calls.ticket_source =
ticket_source.source_id LEFT OUTER JOIN subcategories
ON calls.subcat_id = subcategories.subcat_id WHERE
created_by = 'brett.little' AND (DATE(created_on)
between '2013-03-01' and '2013-08-01') AND
(TIME(created_on) between '1:00:00' and '16:00:00')
It is displaying results when I leave out '(TIME(created_on) between '1:00:00' and '16:00:00')'. Might this have anything to do with the date_format in the beginning of the query?
You'll have to enhance the clause to check the times and dates separately:
WHERE (DATE(created_on) BETWEEN '2013-03-24' and '2013-04-01')
AND (TIME(created_on) BETWEEN '00:00:00' AND '01:00:00')

how to compare two tables fields name with another value in mysql?

I have two tables
table_school
school_open_time|school_close_time|school_day
8:00 AM | 9:00PM | Monday
10:00 AM | 7:00PM | Wednesday
table_college
college_open_time|college_close_time|college_day
10:00 AM | 8:00PM | Monday
10:00 AM | 9:00PM | Tuesday
10:00 AM | 5:00PM | Wednesday
Now I want to select school_open_time school_close time, college_open_time and college_close_time according to today (means college_day=school_day=today), and also if there is no row for a specific day in any of one table then it display blank field ( LEFT JOIN , I think I can use).
Please suggest me best and optimized query for this.
UPDATE:
if there is no open time and close time for school then college_open_time and college_close_time has to be returned( not to be filled in database,just return) as school_open_time and school_close_time. and there always must be college_open_time and college_close_time for a given day
i m using below query
SELECT college_open_time,college_close_time ,school_open_time,
school_close_time FROM tbl_college
LEFT JOIN tbl_school ON school_owner_id=college_owner_id
WHERE college_owner_id='".$_session['user_id']."' AND
college_day='".date('l',time())."'";
it return single row (left hand having some value and right hand having blank value) when there is no row of a given day in table_school, BUT display seven rows with same value on left hand side(college_open_time, college_close_time) and 6 blank row on right hand side (school_open_time and school_close_time)
i need only one row when both table have a row of a given day
but using above query take only first row of corresponding table_school where school_owner_id is 50(let), it not see the condition that school_day name should be given day
More UPDATE #37Stars
There is a little bit problem also Dear,
datatype of school_close_time and school_open time is TIME type
whereas datatype of college_open_time and college_close_time is VARCHAR type.
i used below code given by you but i modified a bit and i m getting close to result,
but now tell me where i have to write IFNULL in below code segment
IFNULL(TIME_FORMAT()) Or TIME_FORMAT(IFNULL())
SELECT TC.owner_id,college_open_time AS collegeOpen,
college_close_time AS collegeClose,
TIME_FORMAT(school_open_time, '%h:%i %p' ) AS schoolOpen,
TIME_FORMAT(school_close_time, '%h:%i %p' ) AS schoolClose
FROM tbl_college TC
LEFT JOIN tbl_school TS ON TS.owner_id = TC.owner_id
AND TC.college_day = TS.school_day
WHERE college_day = DATE_FORMAT(NOW(),'%W')
Solution
Thanks 37stars, u r genious, thanx for the ideo of IFNULL,
i m writing OPTIMUM AND BEST QUERY
SELECT TC.owner_id,college_open_time AS collegeOpen,college_close_time AS
collegeClose, IFNULL(TIME_FORMAT(school_open_time, '%h:%i %p'),college_open_time)
AS schoolOpen,IFNULL(TIME_FORMAT(school_close_time, '%h:%i %p',college_close_time)
AS schoolClose FROM tbl_college TC LEFT JOIN tbl_school TS
ON TS.owner_id = TC.owner_id AND TC.college_day = TS.school_day
WHERE college_day = DATE_FORMAT(NOW(),'%W')
FROM tbl_storecalendar TS LEFT JOIN tbl_delivery_hours TD
ON TD.store_id = TS.store_id
AND TD.del_day = TS.dayName WHERE dayName = DATE_FORMAT( NOW( ) , '%W' )
You want a FULL OUTER JOIN, but unfortunately MySQL doesn't support this. Luckily, there is a workaround by combining a left join and a right join using UNION ALL:
Update: Changed query to answer OP's updated question.
SELECT
COALESCE(school_day, college_day) AS day,
COALESCE(school_open_time, college_open_time) AS school_open_time,
COALESCE(school_close_time, college_close_time) AS school_close_time,
COALESCE(college_open_time, school_open_time) AS college_open_time,
COALESCE(college_close_time, school_close_time) AS college_close_time
FROM (
SELECT * FROM table_school LEFT JOIN table_college ON school_day = college_day
UNION ALL
SELECT * FROM table_school RIGHT JOIN table_college ON school_day = college_day
WHERE school_day IS NULL
) AS T1
You need to add school_day = college_day to your JOIN clause.
SELECT college_open_time, college_close_time, school_open_time, school_close_time
FROM dbo.tbl_college AS TC
LEFT JOIN dbo.tbl_school AS TS ON TS.owner_id = TC.owner_id
AND TS.school_day = TC.college_day
WHERE TC.owner_id = 1
AND college_day = 'tuesday'
I would recommend changing your DB structure to two tables with the following structure:
table institutions:
institution | institution_id
table times:
institution_id | day | open_time | close_time
You could easily put your two existing tables into the new times table, i.e.
INSERT INTO times(institution, day, open_time, close_time)
SELECT 'School', school_day, school_open_time, school_close_time
FROM table_school
And then getting the query results is easy:
SELECT i.institution, t.open_time, t.close_time
FROM times t
LEFT JOIN institutions i on t.institution_id=i.institution_id
WHERE day='Wednesday'
If you want to accomplish this in one query, you'll have to use UNION to put your results together, like this:
SELECT school_open_time AS openTime,`int` AS school_close_time
FROM table_school WHERE school_day=DATE_FORMAT(NOW(),'%W')
UNION
SELECT college_open_time AS openTime,`int` AS college_close_time
FROM table_college WHERE college_day=DATE_FORMAT(NOW(),'%W');
Where DATE_FORMAT(NOW(),'%W') converts to the current day of the week.
However, this method doesn't seem all that great to me. First of all, it won't handle putting NULL methods into the result set for you in the case of a missing record. You could add some IF/ELSE statements to do this for you, but in all honesty, I'd probably just make two separate queries from your PHP code. That way, you can handle each one specifically and control your results more easily from there.

Categories