Get a query to list the records that are on and in between the start and the end values of a particular column for the same Id

后端 未结 2 1693
攒了一身酷
攒了一身酷 2021-01-24 16:21

There is a table with the columns :

USE \'table\';  
insert into person values   
(\'11\',\'xxx\',\'1976-05-10\',\'p1\'),  
(\'11\',\'xxx \',\'1976-06-11\',\'p1\         


        
2条回答
  •  耶瑟儿~
    2021-01-24 16:24

    This can be achived by:

    SELECT Id, PId,
           MIN(Start_Date) AS sdt,
           MAX(Start_Date) as edt,
           IF(`place` <> @var_place_prev, (@var_rank:= @var_rank + 1), @var_rank) AS rank,
           (@var_place_prev := `place`) AS `place`
    FROM person, (SELECT @var_rank := 0, @var_place_prev := "") dummy
    GROUP BY rank, Place;
    

    Example: SQLFiddle

    If you want records to be ordered by ID then:

    SELECT Id, PId,
           MIN(Start_Date) AS sdt,
           MAX(Start_Date) as edt,
           `place`
    FROM(
         SELECT Id, PId,
                Start_Date
                IF(`place` <> @var_place_prev,(@var_rank:= @var_rank + 1),@var_rank) AS rank,
                (@var_place_prev := `place`) AS `place`
         FROM person, (SELECT @var_rank := 0, @var_place_prev := "") dummy
         ORDER BY ID ASC
        ) a
    GROUP BY rank, Place;
    

提交回复
热议问题