Take this example data:
ID Status Date
1 Pending 2/10/2020
2 Pending 2/10/2020
3 Pending 2/10/2020
2 Pending 2/10/2020
2 Pending 2/10/2020
1 Complete 2/15/2020
I need an SQL statement that will group all the data but bring back the current status. So for ID 1 the group by needs a condition that only returns the Completed row and also returned the pending rows for ID 2 and 3.
I am not 100% how to write in the condition for this.
Maybe something like:
SELECT ID, Status, Date
FROM table
GROUP BY ID, Status, Date
ORDER BY ID
The problem with this is the resulting data would look like:
ID Status Date
1 Pending 2/10/2020
1 Complete 2/15/2020
2 Pending 2/10/2020
3 Pending 2/10/2020
But I need:
ID Status Date
1 Complete 2/15/2020
2 Pending 2/10/2020
3 Pending 2/10/2020
What can I do to check for the Completed status so I can only return Completed in the group by?
Do only GROUP BY the ID column. Use MIN() to chose Complete before Pending.
SELECT ID, MIN(Status)
FROM table
GROUP BY ID
ORDER BY ID
To use Date as 'last row indicator', you can:
DECLARE #Src TABLE (
ID int,
Status varchar(20),
Date Date
)
INSERT #Src VALUES
(1, 'Pending' ,'2/10/2020'),
(1, 'Complete' ,'2/15/2020'),
(2, 'Pending' ,'2/10/2020'),
(3, 'Pending' ,'2/10/2020');
SELECT TOP 1 WITH TIES *
FROM #Src
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC)
Result:
ID Status Date
----------- -------------------- ----------
1 Complete 2020-02-15
2 Pending 2020-02-10
3 Pending 2020-02-10
Related
ID
NAME
DATE
STATUS
1
Joe
01-22
Approved
1
Joe
01-22
Pending
2
Bill
02-22
Approved
2
Bill
02-22
Sent back
3
John
01-22
Approved
4
Bob
02-22
Pending
How do I only return one row per ID, placing priority on approved?
Example: for Id 1 I only want the row that is approved and not the one that is pending.
Some Id's may only have 1 record for example ID 4 has just one record and is pending.
What I want is:
IF status = approved and pending for the same Id then keep the approved record and not select the pending record
If status = pending then keep that record
This will preferentially select Approved, then Pending, then everything else. If you don't want "everything else" just filter in the WHERE clause.
select id,
name,
date,
status
from (
select *,
row_number() over
( partition by id
order by case when status = 'Approved' then 1
when status = 'Pending' then 2
else 3
end asc,
date
) as first_by_date_with_approved_precedence
from your_table
) tmp
where first_by_date_with_approved_precedence = 1
It could also be as easy as the following (provided status is not blank or null)
Select Top 1 with ties *
from YourTable
order by row_number() over (partition by id order by Status)
Results
ID NAME DATE STATUS
1 Joe 01-22 Approved
2 Bill 02-22 Approved
3 John 01-22 Approved
4 Bob 02-22 Pending
I have a table of records I want to sort by earliest date first then by userid.
If the user associated to the date also has other records in that table I want to group those under the earliest date.
Desired output
Id UserId Date
1 2 1/1/2020
2 2 2/1/2020
3 2 3/1/2020
4 1 1/2/2020
5 1 2/2/2020
6 3 1/4/2020
7 4 1/5/2020
In this example UserId 2 has the earliest record in that table, so that record should be first followed by his additional records in date asc order
You seems want :
select t.*
from table t
order by min(date) over (partition by userid), date;
Some database product doesn't support window function with order by, so you can do instead :
select t.*, min(date) over (partition by userid) as mndate
from table t
order by mndate, date;
If I understand what you want...
You could do this (sample with DB2 syntax):
SELECT tab.UserId, tab.Date, tab.*
FROM DB2SIS.TABLE_NAME tab
ORDER BY tab.Date ASC, tab.UserId ASC
This way UserId and Date will appear repeatedly. Instead of 'tab.*' use each field you want to show, then UserId and Date will not repeat.
I have a table with the following columns:
ID
Scheduled Date
Status
Target Date
I need to extract 'Status' corresponding to minimum 'Appointment Date' for each ID. If not available then I need to extract status corresponding to the minimum 'Target Date' for that ID.
Sample data:
ID | Scheduled_Date | Status | Target_Date
1 12/11/2017 Completed 12/11/2017
1 12/12/2017 Completed 12/12/2017
2 12/13/2017 Completed 12/13/2017
3 12/14/2017 Pending 12/14/2017
3 12/15/2017 Pending 12/15/2017
4 Confirmed 12/18/2017
4 Confirmed 12/19/2017
5 12/14/2017 Completed 12/14/2017
5 12/15/2017 Pending 12/15/2017
Can you please correct the code that I am trying to write?
SELECT ID,
CASE WHEN ID IS NOT NULL THEN
CASE WHEN MIN(SCHEDULED_DATE) IS NOT NULL
THEN STATUS
ELSE
END
CASE WHEN MIN(TARGET_DATE) IS NOT NULL
THEN STATUS
ELSE ''
END
FROM FIRST_STATUS
Try this query.
SELECT id,
status
FROM yourtable t
WHERE COALESCE (Scheduled_Date,
Target_Date) IN
(SELECT MIN(COALESCE (Scheduled_Date,Target_Date))
FROM yourtable i
WHERE i.ID = t.id
GROUP BY i.ID);
DEMO
Use row_number() analytic function:
select id,
status
from
(
select id,
status,
row_number() over(partition by id, order by nvl(Scheduled_Date,Target_Date)) rn
from yourtable t
)s
where rn=1
;
I have issue with creating a proper SQL expression.
I have table TICKET with column TICKETID
TICKETID
1000
1001
I then have table STATUSHISTORY from where I need to retrieve what was the last time (maximum time) when that ticket entered VENDOR status (last VENDOR status) and when it exited VENDOR status (by exiting VENDOR status I mean the first next INPROG status, but only first INPROG after the VENDOR status, it's always INPROG the next status after VENDOR status). Also it is also possible that VENDOR status for ID does not exist at all in STATUSHISOTRY (then nulls should be returned), but INPROG exists always - it can be before but also and after VENDOR status, if ID is not anymore in VENDOR status.
Here is the example of STATUSHISTORY.
ID TICKETID STATUS DATETIME
1 1000 INPROG 01.01.2017 10:00
2 1000 VENDOR 02.01.2017 10:00
3 1000 INPROG 03.01.2017 10:00
4 1000 VENDOR 04.01.2017 10:00
5 1000 INPROG 05.01.2017 10:00
6 1000 HOLD 06.01.2017 10:00
7 1000 INPROG 07.01.2017 10:00
8 1001 INPROG 02.02.2017 10:00
9 1001 VENDOR 03.02.2017 10:00
10 1001 INPROG 04.02.2017 10:00
11 1001 VENDOR 05.02.2017 10:00
So the result when doing the query from TICKET table and doing the JOIN with table STATUSHISTORY should be:
ID VENDOR_ENTERED VENDOR_EXITED
1000 04.01.2017 10:00 05.01.2017 10:00
1001 05.02.2017 10:00 null
Because for ID 1000 last VENDOR status was at 04.01.2017 and the first INPROG status after the VENDOR status for that ID was at 05.01.2017 while for ID 1001 the last VENDOR status was at 05.02.2017 and after that INPROG status did not happen yet.
If VENDOR did not exist then both columns should be null in result.
I am really stuck with this, trying different JOINs but without any progress.
Thank you in advance if you can help me.
You can do this with window functions. First, assign a "vendor" group to the tickets. You can do this using a cumulative sum counting the number of "vendor" records on or before each record.
Then, aggregate the records to get one record per "vendor" group. And use row numbers to get the most recent records. So:
with vg as (
select ticket,
min(datetime) as vendor_entered,
min(case when status = 'INPROG' then datetime end) as vendor_exitied
from (select sh.*,
sum(case when status = 'VENDOR' then 1 else 0 end) over (partition by ticketid order by datetime) as grp
from statushistory sh
) sh
group by ticket, grp
)
select vg.tiketid, vg.vendor_entered, vg.vendor_exited
from (select vg.*,
row_number() over (partition by ticket order by vendor_entered desc) as seqnum
from vg
) vg
where seqnum = 1;
You can aggregate to get max time, then join onto all of the date values higher than that time, and then re-aggregate:
select a.TicketID,
a.VENDOR_ENTERED,
min( EXIT_TIME ) as VENDOR_EXITED
from (
select TicketID,
max( DATETIME ) as VENDOR_ENTERED
from StatusHistory
where Status = 'VENDOR'
group by TicketID
) as a
left join
(
select TicketID,
DATETIME as EXIT_TIME
from StatusHistory
where Status = 'INPROG'
) as b
on a.TicketID = b.TicketID
and EXIT_TIME >= a.VENDOR_ENTERED
group by a.TicketID,
a.VENDOR_ENTERED
DB2 is not supported in SQLfiddle, but a standard SQL example can be found here.
I have an Assets table that has an audit log of when a particular status of that Asset changes Status... so look's something similar to this
AssetId CapexStatus Date
------- ----------- -----
AM706 1 2017-02-03
AM706 0 2017-02-07
AM706 1 2017-02-10
I then have a timesheet table which has the AssetID and a transaction date on it. I basically want to pull the Capex Status out of the AssetLog table based on the AssetId and the current Capex Status at the time of the transaction date. eg. If the transaction date is 8th Feb then the Capex Status should be "0".
Timesheet table
TimesheetId AssetId TimesheetDate
----------- ------- -------------
1 AM706 2017-02-01
2 AM706 2017-02-08
3 AM706 2017-02-12
I think something like this might do it:
select
t.*,
a.CapexStatus
from
TimeSheet t
outer apply (Select top 1 * from AssetLog al
where
al.AssetID = t.AssetID
and al.Date < t.TimesheetDate
order by al.Date desc) a
create view vwMaxCapex
as
select top 1 capexStatus, date, AssetId from AssetsLog
order by date asc
go
select a.AssetId, a.timesheetDate,
(select capexstatus
from vwMaxCapex
where date<=a.timesheetDate and assetId=a.AssetId) capex
from timetable a