MySql count entries without duplicate datetime - mysql

I have a table which logs all "check-ins" into a system. I want to count all "check-ins" from an user for the current day, but there's the problem that sometimes users check-in like two or three times by mistake in one minute. So I just want to count all entries with a gap from at least two minutes
My current command looks like:
"SELECT event_datetime, LEFT(tag_uid,8) AS tag_uid, count(*) as anzahl FROM events WHERE date(event_datetime) = curdate() GROUP BY tag_uid"
So I only want to count it if the gap between event_datetime is at least two minutes grouped by the tag_uid (the user)
Any ideas how to solve that?

first, you need to calculate the gap for each tag_uid and then you can set conditions as you wish. To calculate the gap you need to have a nested select commands which will get the "first checkIn" and "last checkIn" using min and max command. Use the "timediff" to calculate the time gap.
NOTE: i haven't tried the code, also I've added the select commands so you can see the values to find Errors.
the code would look similar to this:
SELECT
tbl_outer_events.event_datetime,
LEFT(tbl_outer_events.tag_uid,8) AS tag_uid,
count(tbl_outer_events.tag_uid) as anzahl,
(select min(event_datetime) from tbl_events as T1 where ( (t1.tag_uid = tbl_outer_events.tag_uid)) and (date(t1.event_datetime) = curdate()) )as `first_checkin`,
(select max(event_datetime) from tbl_events as T1 where ( (t1.tag_uid = tbl_outer_events.tag_uid)) and (date(t1.event_datetime) = curdate()))as `last_checkin`,
(select TIMEDIFF(max(event_datetime), min(event_datetime)) from tbl_events as T1 where ( (t1.tag_uid = tbl_outer_events.tag_uid)) and (date(t1.event_datetime) = curdate())) as `interval`
FROM events as tbl_outer_events
WHERE ((date(event_datetime) = curdate())
AND (select TIMEDIFF(max(event_datetime), min(event_datetime)) from tbl_events as T1 where ( (t1.tag_uid = tbl_outer_events.tag_uid)) and (date(t1.event_datetime) = curdate())) >= '00:20:00')
GROUP BY tag_uid;
PS: please provide us with sample data or desired outcome. it will help us and you to understand the issue.

Related

MYSQL join most recent record and multiply

I have a stock table and a stock history table, and I am basically trying to write a MySQL statement which will get the value of the stock on a particular day (in this case on the 31st of March), which can only be found by multiplying the cost per unit against what the balance for each item was on the particular day
So far I have :
SELECT
SUM(tbl_stock.cost_per_unit * tbl_stock_history.quantity_balance) as total
FROM
tbl_stock
LEFT JOIN
tbl_stock_history ON tbl_stock.part_ID = tbl_stock_history.part_ID
WHERE
tbl_stock_history.date_of_entry <= '20180331'
and tbl_stock.department = 1
AND tbl_stock.qty > 0
Unfortunately, this code takes the sum of ALL qty_balances found against the part ID's history instead of just the most recent one against the booking_date parameter.
I have tried all the solutions I could find with sub select queries but none of them were playing ball and I feel like I am missing something super obvious!
Any help is greatly appreciated!
I think that this is what you are looking for:
SELECT
SUM(tbl_stock.cost_per_unit * t.quantity_balance) as total
FROM
tbl_stock
LEFT JOIN
(
SELECT * FROM tbl_stock_history
WHERE date_of_entry <= '20180331' ORDER BY date_of_entry DESC limit 1
)
t on tbl_stock.part_ID = t.part_ID
WHERE tbl_stock.department = 1
AND tbl_stock.qty > 0

php - mysql select last inserted record between two dates (every month)

I have a table: box (id autoincrement, net_amount, created_at timestamp);
I need to create a query in php mysql to select the last inserted record every month. Thus to get the net_amount at the end of every month.
I am trying this simple query:
select * from box
where box.created_at < 20055332516028
While the max created_at in my table is 2017-10-14 10:42:30, there is no records when I use the given query, I need to increase the number to get the records!!!
20055332516028 is not a Unix timestamp. You need to get timestamp of the end of the previous month, something like this:
$date = new DateTime();
$date->setDate($date->format('Y'),$date->format('m'),1);
$date->setTime(0,0,0);
$date->sub(new DateInterval('PT1S'));
$endOfMonth = $date->getTimestamp();
and then use it in a query:
select * from box where box.created_at < unix_timestamp(?) order by box.created_at desc limit 1
if i understand your problem your looking for this:-
SELECT b1.*
FROM box b1 LEFT JOIN box b2
ON (b1.name = b2.name AND b1.id < b2.id)
WHERE b1.created_at < PUT YOUR DATE and b2.id IS NULL;
Hope it helps

Generating complex sql tables

I currently have an employee logging sql table that has 3 columns
fromState: String,
toState: String,
timestamp: DateTime
fromState is either In or Out. In means employee came in and Out means employee went out. Each row can only transition from In to Out or Out to In.
I'd like to generate a temporary table in sql to keep track during a given hour (hour by hour), how many employees are there in the company. Aka, resulting table has columns HourBucket, NumEmployees.
In non-SQL code I can do this by initializing the numEmployees as 0 and go through the table row by row (sorted by timestamp) and add (employee came in) or subtract (went out) to numEmployees (bucketed by timestamp hour).
I'm clueless as how to do this in SQL. Any clues?
Use a COUNT ... GROUP BY query. Can't see what you're using toState from your description though! Also, assuming you have an employeeID field.
E.g.
SELECT fromState AS 'Status', COUNT(*) AS 'Number'
FROM StaffinBuildingTable
INNER JOIN (SELECT employeeID AS 'empID', MAX(timestamp) AS 'latest' FROM StaffinBuildingTable GROUP BY employeeID) AS LastEntry ON StaffinBuildingTable.employeeID = LastEntry.empID
GROUP BY fromState
The LastEntry subquery will produce a list of employeeIDs limited to the last timestamp for each employee.
The INNER JOIN will limit the main table to just the employeeIDs that match both sides.
The outer GROUP BY produces the count.
SELECT HOUR(SBT.timestamp) AS 'Hour', SBT.fromState AS 'Status', COUNT(*) AS 'Number'
FROM StaffinBuildingTable AS SBT
INNER JOIN (
SELECT SBIJ.employeeID AS 'empID', MAX(timestamp) AS 'latest'
FROM StaffinBuildingTable AS SBIJ
WHERE DATE(SBIJ.timestamp) = CURDATE()
GROUP BY SBIJ.employeeID) AS LastEntry ON SBT.employeeID = LastEntry.empID
GROUP BY SBT.fromState, HOUR(SBT.timestamp)
Replace CURDATE() with whatever date you are interested in.
Note this is non-optimal as it calculates the HOUR twice - once for the data and once for the group.
Again you are using the INNER JOIN to limit the number of returned row, this time to the last timestamp on a given day.
To me your description of the FromState and ToState seem the wrong way round, I'd expect to doing this based on the ToState. But assuming I'm wrong on that the following should point you in the right direction:
First, I create a "Numbers" table containing 24 rows one for each hour of the day:
create table tblHours
(Number int);
insert into tblHours values
(0),(1),(2),(3),(4),(5),(6),(7),
(8),(9),(10),(11),(12),(13),(14),(15),
(16),(17),(18),(19),(20),(21),(22),(23);
Then for each date in your employee logging table, I create a row in another new table to contain your counts:
create table tblDailyHours
(
HourBucket datetime,
NumEmployees int
);
insert into tblDailyHours (HourBucket, NumEmployees)
select distinct
date_add(date(t.timeStamp), interval h.Number HOUR) as HourBucket,
0 as NumEmployees
from
tblEmployeeLogging t
CROSS JOIN tblHours h;
Then I update this table to contain all the relevant counts:
update tblDailyHours h
join
(select
h2.HourBucket,
sum(case when el.fromState = 'In' then 1 else -1 end) as cnt
from
tblDailyHours h2
join tblEmployeeLogging el on
h2.HourBucket >= el.timeStamp
group by h2.HourBucket
) cnt ON
h.HourBucket = cnt.HourBucket
set NumEmployees = cnt.cnt;
You can now retrieve the counts with
select *
from tblDailyHours
order by HourBucket;
The counts give the number on site at each of the times displayed, if you want during the hour in question, we'd need to tweak this a little.
There is a working version of this code (using not very realistic data in the logging table) here: rextester.com/DYOR23344
Original Answer (Based on a single over all count)
If you're happy to search over all rows, and want the current "head count" you can use this:
select
sum(case when t.FromState = 'In' then 1 else -1) as Heads
from
MyTable t
But if you know that there will always be no-one there at midnight, you can add a where clause to prevent it looking at more rows than it needs to:
where
date(t.timestamp) = curdate()
Again, on the assumption that the head count reaches zero at midnight, you can generalise that method to get a headcount at any time as follows:
where
date(t.timestamp) = "CENSUS DATE" AND
t.timestamp <= "CENSUS DATETIME"
Obviously you'd need to replace my quoted strings with code which returned the date and datetime of interest. If the headcount doesn't return to zero at midnight, you can achieve the same by removing the first line of the where clause.

Selecting ALL Max Values SQL query

I am working with two tables in this query Table 1: admit, Table 2: Billing.
What I want to do is show people who are admitted to our crisis services (program codes '44282' and '44283'). For these people, I want to show their insurance, which is under the field guarantor_id in the Billing Table. To do this, I need to show ALL the max coverage effective dates cov_effective_date where the coverage effective date is less than the admission date preadmit_admission_date and the coverage expiration date cov_expiration_date is greater than the admission date (or Is Null). The code I have right now does everything I want, but doesn’t get all the max coverage effective dates. So if someone had two different insurances that began on the same date it will only show one and I want it show both.
Select
A.patid
,A.episode_number
,A.preadmit_admission_date
,A.program_code
,A.program_value
,A.c_date_of_birth
,A.guarantor_id
,max(A.cov_effective_date) as "MaxDate"
from(
Select
SA.patid
,SA.episode_number
,SA.preadmit_admission_date
,SA.program_code
,SA.program_value
,SA.c_date_of_birth
,BGE.guarantor_id
,BGE.cov_effective_date
From System.view_episode_summary_admit as "SA"
Left Outer Join
(Select
BG.patid
,BG.episode_number
,BG.guarantor_id
,BG.cov_effective_date
,BG.cov_expiration_date
from System.billing_guar_emp_data as "BG"
Inner Join
(Select patid, episode_number, preadmit_admission_date
from System.view_episode_summary_admit ) as "A"
On
(A.patid = BG.patid) and (A.episode_number = BG.episode_number)
Where
BG.cov_effective_date <= preadmit_admission_date and
(BG.cov_expiration_date >= preadmit_admission_date or
BG.cov_expiration_date Is Null)
) as "BGE"
on
(BGE.patid = SA.patid) and (BGE.episode_number = SA.episode_number)
Where
(program_code = '44282' or program_code = '44283' )
and preadmit_admission_date >= {?Start Date}
and preadmit_admission_date <= {?End Date}
) A
Group By Patid, Episode_number
Sorry this is such a psuedo answer.
Select (your fields)
from (your entire query)bg
left join
(select patid, max(cov_effective_date) maxdate from system.billing_guar_emp_data group by patid) maxdate
on maxdate.patid = bg.patidate
Remove the group bys for the aggregate...you can now refer to maxdate.maxdate as a field in your opening select statement. Might be a better place to join this maxdate than joined at the very end of the query (possibly right under BG in the from statement), but psuedo code right? :) Hopefully you can apply the concept, let me know I'm free (freer?) in the afternoon if you need more.

MYSQL - find and show all duplicates within date difference critria

This query below selects all rows that have a row with the same father registering 335 days or less since earlier registration. Is there a way to edit this query so that it does not eliminate the duplicate row in the output? I need to see all instances of the registration for that father within 335 days of each other.
SELECT * FROM ymca_reg a later
WHERE NOT EXISTS (
SELECT 1 FROM ymca_reg a earlier
WHERE
earlier.Father_First_Name = later.Father_First_Name
AND earlier.Father_Last_Name = later.Father_Last_Name
AND (later.Date - earlier.Date < 335) AND (later.Date > earlier.Date)
My current query is:
SELECT ymca_reg.* FROM ymca_reg WHERE (((ymca_reg.Year) In (SELECT Year FROM ymca_reg As Tmp
GROUP BY Year, Father_Last_Name, Father_First_Name
HAVING Count(*)>1
And Father_Last_Name = ymca_reg.Father_Last_Name
And Father_First_Name = ymca_reg.Father_First_Name)))
ORDER BY ymca_reg.Year, ymca_reg.Father_Last_Name, ymca_reg.Father_First_Name
This query does return all the duplicates for review correctly, but it's terribly slow because it doesn't use a join and as soon as I add the date criteria it only returns the later row. Thanks.
I think you want something like this:
SELECT *
FROM ymca_reg later
WHERE EXISTS (SELECT 1
FROM ymca_reg earlier
WHERE earlier.Father_First_Name = later.Father_First_Name AND
earlier.Father_Last_Name = later.Father_Last_Name AND
abs(later.Date - earlier.Date) < 335 and
later.Date <> earlier.Date
);
This should return all records that have such duplicates. Note that "later" and "earlier" are no longer really apt descriptions, but I left the names so you can see the similarity to your query.