I'm trying to find a way to display the last event held (last date and time) in an events table whilst displaying all the columns for that event without using ORDER BY.
For example:
SELECT * from Events
where dateheld in (select max(dateheld) from events)
AND starttime in (select max(starttime) from events)
When I put MAX starttime, it displays nothing. When I put MIN starttime it works but displays the earliest time of that date and not the latest.
I guess you could print out your records, throw them down the stairs, and the ones that go farthest have the "lightest" dates. You cannot sort without order by. It's like wanting water that isn't wet. Unless your data naturally comes out in the order you want, you MUST sort.
Of course, if you want only the record that has the absolute most recent date, and don't need more than just that one record, then
SELECT yourdatetimefield, ...
FROM yourtable
HAVING yourdatetimefield = MAX(yourdatetimefield)
If you are only looking for the latest item:
EDIT gets a little more complicated when you have seperate date and time fields, but this should work. This is a ridiculous kludge for a situation where date and time should be stored in one field.
SELECT *
FROM (
SELECT *
FROM Events
WHERE dateTime = (SELECT MAX(dateheld) FROM Events)
) temp
WHERE starttime = (SELECT MAX(starttime) FROM (
SELECT *
FROM Events
WHERE dateTime = (SELECT MAX(dateheld) FROM Events)
) temp 2 )
Related
So this problem has been bugging me a little for the last week or so. I'm working with a database which hasn't exactly been designed in a way that I like and I'm having to do a lot of work-arounds to get the queries to function in a way I would like.
Essentially, I'm trying to remove duplicate entries that occur as a result of an instance caused by a previous entry. For the sake of argument say that a customer places an order or issues a job (this only occurs once) but as a result of the interactions a series of other rows are created to represent, sub-orders or jobs. Essentially, all duplicate records should have the same finish time so what I'm trying to create is a query which will return the record which has the earliest start time and ignore all other records which have the same finish time. All this occurs within the same table.
Something like:
select starttime
, endtime
, description
, entrynumber
from table
where starttime = min
and endtime = endtime
Probably what you want is something like this:
;WITH OrderedTable AS
(
Select ROW_NUMBER() OVER (PARTITION BY endtime ORDER BY starttime) as rn, starttime, endtime, description, entrynumber
From Table
)
Select starttime, endtime, description, entrynumber
FROM OrderedTable
WHERE rn=1
What this does is group all the rows with the same end time, ordered by start time and give them an additional "row number" column starting at 1 and increasing. If you filter by rn = 1, you get only the earliest start time rows, ignoring the rest.
I am having a SQLite database which contains a table Events with start and end dates. I would like to get a Set (could be an array without duplicates) of dates that they at least have an Event on that day let's say from 1st of August to 20th of August.
Let's take some example events:
Event 1 from 02.08.2016 to 07.08.2016
Event 2 from 10.08.2016 to 12.08.2016
Event 3 from 11.08.2016 to 15.08.2016
Then the outcome should be:
[02.08.2016, 03.08.2016, 04.08.2016, 05.08.2016, 06.08.2016, 07.08.2016, 10.08.2016, 11.08.2016, 12.08.2016, 13.08.2016, 14.08.2016, 15.08.2016]
where 11.08.2016 and 12.08.2016 are not repeating.
NB: I am expecting an answer that could solve this problem only using SQL rather combining some programming code. I need that on a mobile device (iOS) where I am trying to optimize the user experience and performance.
Here is an example of creating a date table with recursive CTE and using it to select dates you need:
WITH RECURSIVE
cnt(dt) AS
(
SELECT MIN(startDate) FROM Events
UNION ALL
SELECT date(dt,'+1 day') FROM cnt
WHERE dt < (SELECT MAX(endDate) FROM Events)
LIMIT 10000
)
SELECT DISTINCT dt
FROM cnt
JOIN Events ON dt BETWEEN startDate AND endDate
ORDER BY dt;
SQL fiddle demo
I am working on a report application for rotating equipment. We calculate the status of the equipment every 3 hours and store the calculation in an Oracle database.
Before the report presented only the "current state" (where we only retrieved the latest calculation). But now the user is going to have the option to scroll back in time and look at earlier calculations.
SELECT *
FROM G_RunningHoursEvent
WHERE GRTE_TagName='#!VARIABLE_TAGNAME#' AND
GRTE_ValuesUpdate IN (SELECT MAX(GRTE_ValuesUpdate)
FROM G_RunningHoursEvent
WHERE GRTE_TagName='#!VARIABLE_TAGNAME#')
SQL is not my strongest suit and most of colleagues are on holiday. I need some tips on how I can extract the latest calculation closest to the new variable #!VARIABLE_TIME#
Is there someone that have any suggestions ?
If I understand correctly, the user will select a datetime value and you need to select the Event record which is closest to that time.
The following query does some magic in the sub-query to establish the record which is closest to the #!VARIABLE_TIME# value.
select
from g_runninghoursevent
where grte_tagname = '#!VARIABLE_TAGNAME#'
and grte_valuesupdate in
( select grte_valuesupdate
from ( with data as
( select grte_valuesupdate
, abs(grte_valuesupdate - #!VARIABLE_TIME#) tdiff
from g_runninghoursevent
where grte_tagname = '#!VARIABLE_TAGNAME#` )
select grte_valuesupdate
, rank() over (order by tdiff asc) rnk
from data )
where rnk = 1 )
Notes
The ABS() call means the sub-query will return the record with the smallest difference, either before or after the input parameter.
The sub-query uses IN rather than equality because you might get a tie for the smallest difference
I have assumed #!VARIABLE_TIME# is a datetime; if it is a string you will need to cast it to a date with teh appropriate mask.
This query should solve your problem:
SELECT *
FROM G_RunningHoursEvent
WHERE GRTE_TagName='#!VARIABLE_TAGNAME#' AND
TRUNC(GRTE_ValuesUpdate) = (SELECT TRUNC(GRTE_ValuesUpdate)
FROM (SELECT GRTE_ValuesUpdate
FROM G_RunningHoursEvent
WHERE GRTE_TagName='#!VARIABLE_TAGNAME#'
ORDER BY GRTE_ValuesUpdate DESC)
WHERE ROWNUM = 1);
Doing this you are ordering the G_RunningHoursEvent records by date having the closest record (in time) in the 1st row.
With the other SELECT, you just extract this 1st record.
I am trying to list the latest event (only one row output)
Basically the very last date of the event and the very last time of the event.
The below code doesn't work if it is max(starttime), but it works if it is min(starttime)
However, if I do min(starttime), it'll tell me the last date of the event but the first event of that last date.
I would like to get the result of the last event time of the last date. (therefore only 1 row output)
Any ideas?
SELECT * from Events
where dateheld in (select max(dateheld) from events)
AND starttime in (select max(starttime) from events)
The issue seems to be the logic as your WHERE statement could be generating two disjoint sets (the max(time) of the table does not share a row with the max(date)). What about something such as the following: (DISTINCT ensures only one record)
SELECT MAX(dateheld) AS 'MaxDate', starttime
FROM Events
WHERE starttime in
(SELECT MAX (starttime) AS temp FROM events)
you can limit your result to the top 1 record returned:
select * from events
order by dateheld, starttime desc
limit 1
edit to meet new requirement
select max(starttime) as maxstart, dateheld
from events
where dateheld = (select max(dateheld) as maxdateheld from events)
Table testTable has 4 columns
sessionid int
started datetime
ended datetime
SessionIsRunning bool - will be true if last session has not yet ended. Max only one record can be true at anytime since at the most only one session can be running. If no session is running then all records have this as false.
Given two dates say fromDate and toDate, how do I get the first session that started on or after fromDate and the last session that ended on or before toDate. Tricky condition is that if a session is in progress and it's start date >= fromDate we need this. I am guessing it might not be possible to get both the min and max session id in one sql statement and keep the code readable and easy to maintain. Two separate sql statements is ok. one to get min and one to get max. Then I can query rows using between min and max.
This last statement explains it in a different way. Get all sessions that started or was running and ended or was running between from/to dates thank you
After considering your edits and the comments regarding BETWEEN, this should give you the result set you need. It will pull any record where SessionIsRunning = true as well as sessions thats started AND ended in the date range.
SELECT * FROM testTable tt
WHERE (tt.started >= fromDate AND tt.started < DATEADD(DAY, 1, toDate)
AND tt.ended >= fromDate AND tt.ended < DATEADD(DAY, 1, toDate))
OR SessionIsRunning = true
ORDER BY tt.sessionid
Getting only the first and last value in a single query (because your question made me curious how to actually write this, even though that doesn't appear to be what you're really asking):
SELECT * FROM
(SELECT TOP 1 * FROM ATable ORDER BY AColumn ASC) first
UNION
SELECT * FROM
(SELECT TOP 1 * FROM ATable ORDER BY AColumn DESC) last