Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.
id home datetime player resource
---|-----|------------|--------|---------1|10|04/03/2009| john |3992|11|04/03/2009| juliet |2445|12|04/03/2009| borat |5553|10|03/03/2009| john |3004|11|03/03/2009| juliet |2006|12|03/03/2009| borat |5007|13|24/12/2008| borat |6008|13|01/01/2009| borat |700
I need to select each distinct home holding the maximum value of datetime.
Result would be:
id home datetime player resource
---|-----|------------|--------|---------1|10|04/03/2009| john |3992|11|04/03/2009| juliet |2445|12|04/03/2009| borat |5558|13|01/01/2009| borat |700
I have tried:
-- 1 ..by the MySQL manual: SELECTDISTINCT
home,
id,datetimeAS dt,
player,
resource
FROM topten t1
WHEREdatetime=(SELECT
MAX(t2.datetime)FROM topten t2
GROUPBY home)GROUPBYdatetimeORDERBYdatetimeDESC
Doesn't work. Result-set has 130 rows although database holds 187. Result includes some duplicates of home.
-- Test dataDECLARE@TestTable TABLE(id INT, home INT, date DATETIME,
player VARCHAR(20), resource INT)INSERTINTO@TestTable
SELECT1,10,'2009-03-04','john',399UNIONSELECT2,11,'2009-03-04','juliet',244UNIONSELECT5,12,'2009-03-04','borat',555UNIONSELECT3,10,'2009-03-03','john',300UNIONSELECT4,11,'2009-03-03','juliet',200UNIONSELECT6,12,'2009-03-03','borat',500UNIONSELECT7,13,'2008-12-24','borat',600UNIONSELECT8,13,'2009-01-01','borat',700-- AnswerSELECT id, home, date, player, resource
FROM(SELECT id, home, date, player, resource,
RANK()OVER(PARTITIONBY home ORDERBY date DESC) N
FROM@TestTable
)M WHERE N =1-- and if you really want only home with max dateSELECT T.id, T.home, T.date, T.player, T.resource
FROM@TestTable T
INNERJOIN(SELECT TI.id, TI.home, TI.date,
RANK()OVER(PARTITIONBY TI.home ORDERBY TI.date) N
FROM@TestTable TI
WHERE TI.date IN(SELECT MAX(TM.date)FROM@TestTable TM))TJ
No matter what stage you're at in your education or career, TuteeHUB will help you reach the next level that
you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice
sessions to improve your knowledge and scores.
manpreet
Best Answer
2 years ago
My table is:
I need to select each distinct
home
holding the maximum value ofdatetime
.Result would be:
I have tried:
Doesn't work. Result-set has 130 rows although database holds 187. Result includes some duplicates of
home
.