October 31, 2018 at 4:56 pm
Hello,
I have a table called Transaction
Date ——- Date Time ——— Status
1/1/18 6:55 400
1/12/18 6:20 500
1/12/18 6:35 400
1/12/18 6:40 400
I’m trying to get
1/1/18 6:55 400
1/12/18 6:40 400
Becauae both rows have status = 400 and they are the max time of each date.
How do I write a sql to accomplish that?
Thanks in advance.
October 31, 2018 at 5:30 pm
irehman - Wednesday, October 31, 2018 4:56 PMHello,I have a table called TransactionDate ——- Date Time ——— Status1/1/18 6:55 4001/12/18 6:20 5001/12/18 6:35 4001/12/18 6:40 400I’m trying to get 1/1/18 6:55 4001/12/18 6:40 400Becauae both rows have status = 400 and they are the max time of each date.How do I write a sql to accomplish that?Thanks in advance.
Something like the following should do the trick...
WITH
cte_AddRN AS (
SELECT
t.[Date],
t.[Time],
t.[Status],
rn = ROW_NUMBER() OVER (PARTITION BY t.[Date] ORDER BY t.[Time] DESC)
FROM
dbo.Transactions t
)
SELECT
*
FROM
cte_AddRN ar
WHERE
ar.rn = 1;
October 31, 2018 at 6:49 pm
Jason A. Long - Wednesday, October 31, 2018 5:30 PMirehman - Wednesday, October 31, 2018 4:56 PMHello,I have a table called TransactionDate ——- Date Time ——— Status1/1/18 6:55 4001/12/18 6:20 5001/12/18 6:35 4001/12/18 6:40 400I’m trying to get 1/1/18 6:55 4001/12/18 6:40 400Becauae both rows have status = 400 and they are the max time of each date.How do I write a sql to accomplish that?Thanks in advance.Something like the following should do the trick...
WITH
cte_AddRN AS (
SELECT
t.[Date],
t.[Time],
t.[Status],
rn = ROW_NUMBER() OVER (PARTITION BY t.[Date] ORDER BY t.[Time] DESC)
FROM
dbo.Transactions t
)
SELECT
*
FROM
cte_AddRN ar
WHERE
ar.rn = 1;
This would have been a whole lot easier if they hadn't split the date and time into two columns.
--Jeff Moden
Change is inevitable... Change for the better is not.
November 1, 2018 at 5:13 am
Jason A. Long - Wednesday, October 31, 2018 5:30 PMirehman - Wednesday, October 31, 2018 4:56 PMHello,I have a table called TransactionDate ——- Date Time ——— Status1/1/18 6:55 4001/12/18 6:20 5001/12/18 6:35 4001/12/18 6:40 400I’m trying to get 1/1/18 6:55 4001/12/18 6:40 400Becauae both rows have status = 400 and they are the max time of each date.How do I write a sql to accomplish that?Thanks in advance.Something like the following should do the trick...
WITH
cte_AddRN AS (
SELECT
t.[Date],
t.[Time],
t.[Status],
rn = ROW_NUMBER() OVER (PARTITION BY t.[Date] ORDER BY t.[Time] DESC)
FROM
dbo.Transactions t
)
SELECT
*
FROM
cte_AddRN ar
WHERE
ar.rn = 1;
Here is a boring version - no CTE's, no row numbering:
SELECT [Date], MAX([Time], Status
from dbo.Transactions
group by [Date], Status
_____________
Code for TallyGenerator
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply