Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL- How to fetch occurrence in MySQL

Tags:

i have data in MySQL table as

enter image description here

i want to fetch employee records occurrence as shown below

enter image description here

Sample DATA:

CREATE TABLE `login_details` (
  `idlogin_details` int(11) NOT NULL AUTO_INCREMENT,
  `emp_id` varchar(45) DEFAULT NULL,
  `date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`idlogin_details`)
)

INSERT INTO `login_details` VALUES (1,'3','2018-07-11 05:18:59'),(2,'2','2018-07-11 05:18:59'),(3,'4','2018-07-11 05:18:59'),(4,'1','2018-07-11 05:18:59'),(5,'1','2018-07-13 05:18:59'),(6,'2','2018-07-13 05:18:59'),(7,'3','2018-07-12 05:18:59'),(8,'3','2018-07-13 05:18:59'),(9,'4','2018-07-13 05:18:59'),(10,'5','2018-07-13 05:18:59');
like image 562
harish_sng Avatar asked Jul 13 '18 06:07

harish_sng


People also ask

How do you count occurrences in SQL?

COUNT(ID) as NumberOfOccurance:- Counting the number of occurrence of a ID. group by – It is necessary in aggregate function like 'count()' otherwise it will give error. having (COUNT(ID)>1) -Select those rows which count of ID value is greater than 1, that's why it shows '0' and '1'.

How do you find the occurrence of a character in a string in MySQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0. This function performs a case-insensitive search.


1 Answers

I don't know if you intend for that occurrence column to appear in the result set. Assuming you don't, you just need an ORDER BY clause. Assuming you do, then we have to do more work. One simple approach is to use a correlated subquery to find the occurrence number:

SELECT
    idlogin_details,
    emp_id,
    date,
    (SELECT COUNT(*) FROM login_details t2
     WHERE t1.emp_id = t2.emp_id AND t2.date <= t1.date) occurrence
FROM login_details t1
ORDER BY
    emp_id, date;

enter image description here

Demo

like image 57
Tim Biegeleisen Avatar answered Oct 12 '22 07:10

Tim Biegeleisen