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')
Related
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
I have a table of hours which looks like :
I want to sum the hours_spent results for this week only and group the results by the created_by person. I have this query which returns the correct data for showing only results in this week :
SELECT staff_id, first_name, last_name, date_entered, `hours_spent` as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id where yearweek(`date_entered`) = yearweek(curdate());
But when I add the SUM(hours_spent) as total_hours and group by staff_id like the example below I get 0 results.
SELECT staff_id, date_entered, first_name, last_name, SUM(`hours_spent`) as total_hours FROM hours LEFT JOIN staff ON hours.created_by = staff.staff_id group by staff_id having yearweek(`date_entered`) = yearweek(curdate());
I'm assuming it's not working because the Having part of my statement doesn't return individual rows of dates so it breaks.
I feel like I am doing this the hard way. Should I be trying to run a second summing query on the results of the first query rather than combine it all into one (I was hoping for cleanliness). Or should I be using a subquery to filter out the dates that aren't this week then group the totals if so how could I accomplish this?
I got what I was expecting with :
SELECT staff.first_name,staff.last_name, sum(hours_spent)
FROM hours
LEFT JOIN staff ON hours.created_by = staff.staff_id
WHERE yearweek(date_entered,1) = (yearweek(curdate(),1)-1)
GROUP BY created_by
I currently have the following tables with:
TABLE klusbonnen_deelnemers:
bonnummer (varchar) - order number
adres (varchar) - order adres
deelnemer (varchar) - user
binnen (date) - date order received
klaar (date) - original order milestone
datum_gereed (date) - date order completed
gereed (varchar) - YES or NO (YES= completed NO= Not yet completed)
datum_factuur (date) - date when user marked order completed (button clicked)
factuur (varchar) - weeknumber order completed
One order(bonnummer) can have multiple users (deelnemer) who all have to mark the order "completed" (datum_gereed). Only when ALL users (deelnemer) have marked an order (bonnummer) "completed" (datum_gereed) the order IS "completed".
I am trying to write a query that gives me:
All completed orders (bonnummer) in a given timespan (last month).
However...
The completion date (datum_gereed) should hold the LAST date (as that is the actual total completion date).
The list should have the Order (bonnummer) with the latest "marked completed" date (datum_factuur) on top (sort DESC) (of course only when all users (deelnemer) have completed the order (all users(deelnemers) having gereed="YES")
So far i have this:
SELECT DISTINCT tbl1.bonnummer AS 'KLUSBONNUMMER', tbl1.adres AS 'ADRES',
tbl1.binnen AS 'BINNENGEKOMEN OP', tbl1.klaar AS 'ORIGINELE STREEFDATUM',
tbl1.datum_gereed AS 'GEREEDGEKOMEN OP', tbl1.factuur AS 'WEEKNUMMER'
FROM klusbonnen_deelnemers AS tbl1
INNER JOIN
( SELECT tbl2.bonnummer
FROM klusbonnen_deelnemers AS tbl2
WHERE tbl2.bonnummer NOT IN (
SELECT tbl3.bonnummer
FROM klusbonnen_deelnemers AS tbl3
WHERE tbl3.gereed = 'NEE')
) AS tbl4 ON tbl1.bonnummer = tbl4.bonnummer
INNER JOIN
( SELECT bonnummer, MAX(datum_gereed) AS 'MAXDATUM'
FROM klusbonnen_deelnemers
GROUP BY bonnummer
) MAXFILTER ON tbl1.bonnummer = MAXFILTER.bonnummer
AND tbl1.datum_gereed = MAXFILTER.MAXDATUM
WHERE tbl1.datum_factuur BETWEEN NOW() - INTERVAL 2 MONTH AND NOW()
ORDER BY tbl1.bonnummer DESC
This query DOES work, however i think this can be done in a much simpler way.
On top of that the query only works in my navicat editor. Calling this query on my "live" website gives an error (subquery in WHERE clause...) (i do have all login correct as other queries DO work).
Anyone out there who can help (simplify) this query? Thx...
this part:
INNER JOIN (SELECT tbl2.bonnummer
FROM klusbonnen_deelnemers AS tbl2
WHERE tbl2.bonnummer NOT IN
(SELECT tbl3.bonnummer
FROM klusbonnen_deelnemers AS tbl3
WHERE tbl3.gereed = 'NEE')) AS tbl4
ON tbl1.bonnummer = tbl4.bonnummer
seems like useless. try to use gereed <> 'NEE' in the "very-bottom"-WHERE
SELECT DISTINCT
kd.bonnummer AS 'KLUSBONNUMMER',
kd.adres AS 'ADRES',
kd.binnen AS 'BINNENGEKOMEN OP',
kd.klaar AS 'ORIGINELE STREEFDATUM',
kd.datum_gereed AS 'GEREEDGEKOMEN OP',
kd.factuur AS 'WEEKNUMMER'
FROM klusbonnen_deelnemers AS kd
INNER JOIN (
SELECT bonnummer, MAX(datum_gereed) AS 'MAXDATUM'
FROM klusbonnen_deelnemers
GROUP BY bonnummer
) AS MAXFILTER
ON (kd.bonnummer = MAXFILTER.bonnummer AND kd.datum_gereed = MAXFILTER.MAXDATUM)
WHERE
kd.gereed <> 'NEE'
kd.datum_factuur BETWEEN NOW() - INTERVAL 2 MONTH AND NOW()
ORDER BY
kd.bonnummer DESC
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)
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.