The table from which I have tried to read
Here I am trying to read the rows which has the latest TransactionDate and grouped by StackHistoryID.
So I thought of using "order by TransactionDate desc" first then the latest row will be top and if I use group by after that it will give what i have wanted. But I figured that, We can not use groupby after using orderby. So I struck here, Is there any way to get what I have wanted using a single query.
UPDATE:
select ID, Max(TransactionDate) from Stacks group by StackHistoryID
But the ID for the first row in this output should be 9.
use MAX()
select StackHistoryID, Max(TransactionDate)
from Stacks
group by StackHistoryID;
And simple query with ID, use MAX; (if the ID is incremental, ie higher id can not have lower date):
select Max(ID),StackHistoryID, Max(TransactionDate)
from Stacks
group by StackHistoryID;
And if your ID is not incremental together with date, ie you could have a higher ID with lower date... Then you could do something like:
select alls.ID, s.StackHistoryID, s.TransactionDate
from
(
select StackHistoryID as StackHistoryID,
Max(TransactionDate) as TransactionDate
from stacks
group by StackHistoryID desc
) s, Stacks alls
where
alls.StackHistoryID = s.StackHistoryID
and
alls.TransactionDate = s.TransactionDate
order by StackHistoryID
;
If you want all data for stackhistoryid
with transactiondate
sorted. then go for.
select * from stacks order by StackHistoryID, TransactionDate desc;
If you need only latest date go for result specified by @MrSimpleMind
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.