Below is my table script.
I have multiple entries for the same study id with different api_cron_job_id, created_at and status can be Complete OR In Progress.
basically, we are inserting records based on study id with different values for all columns and timestamps in created at the column for e.g. here is the insert script
INSERT INTO `analytics_cron_refresh_time` (`id`, `study_id`, `client_id`, `last_completion_date`, `status`, `created_at`, `modifed_at`, `api_cron_job_id`)
VALUES ('2798d9b0-ef59-496e-ba21-f2d7bdc9518d', 'c5d52f86-c0e3-46e3-a164-ac321329d78e', '654111', '2023-07-06 13:12:55.598', 'Complete', '2023-07-06 13:12:50.000', '2023-07-06 13:12:55.598', 147);
Now I want to select recent 2 entries for each study_id
Can you please help me, and please someone format this question, its my first question so all folks understand it.
CREATE TABLE `analytics_cron_refresh_time` (
`id` varchar(100) NOT NULL,
`study_id` varchar(100) DEFAULT NULL,
`client_id` varchar(45) DEFAULT NULL,
`last_completion_date` datetime(3) DEFAULT NULL,
`status` varchar(45) DEFAULT NULL,
`created_at` datetime(3) DEFAULT NULL,
`modifed_at` datetime(3) DEFAULT NULL,
`api_cron_job_id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`),
UNIQUE KEY `api_cron_job_id_UNIQUE` (`api_cron_job_id`),
KEY `idx_study_id` (`study_id`,`api_cron_job_id`),
KEY `idx_study_id_status` (`status`,`study_id`,`api_cron_job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=52 DEFAULT CHARSET=latin1
*I tried below script *
SELECT t1.*
FROM analytics_cron_refresh_time t1
LEFT JOIN analytics_cron_refresh_time t2
ON t1.study_id = t2.study_id AND t1.created_at < t2.created_at AND t1.status
WHERE t1.status = 'Complete'
GROUP BY t1.study_id
HAVING COUNT(*) > 2
ORDER BY t1.created_at DESC;
but getting incorrect data.
2
Answers
try this
you can find more about how session variables work here also notice that select would have 2 more columns if you wanna get rid of them try selecting specific columns in outer select instead of *
This should help you in finding the latest two records of each group by study_id