Sort the Whole Group Based On Date

Viewed 35

I have data following data, where i want to sort whole group based on date.

Create Table CustomerData
(
 Id Integer,
 GroupId Varchar(25),
 CName Varchar(25),
 Product Varchar(25),
 StartDate Date,
 EndDate Date,
 Premium Integer,
 GroupMo Varchar(25)
)

Insert Into CustomerData Values(1,'U001','Uday Dodiya','Motor Policy','2021-08- 
19','2022-08-18',2500,'9601629656')
Insert Into CustomerData Values(2,'K001','Kalpesh Shah','Health Policy','2021-08- 
02','2022-08-01',500,'9911629656')
Insert Into CustomerData Values(3,'U001','Brinda Dodiya','PA Policy','2021-08-02','2022- 
08-01',200,'9601629656')
Insert Into CustomerData Values(4,'Z001','Zalak Mer','PA Policy','2021-08-16','2022-08- 
15',2500,'9801629656')
Insert Into CustomerData Values(5,'H001','Harsh Rathod','WC Policy','2021-08-02','2022- 
08-01',4500,'7788995566')
Insert Into CustomerData Values(6,'H001','Het Dodiya','Motor Policy','2021-08-29','2022- 
08-28',2900,'7788995566')
Insert Into CustomerData Values(7,'U001','Gopal Dodiya','Other Policy','2021-08- 
31','2022-08-30',3000,'9601629656')
Insert Into CustomerData Values(8,'U001','Gopal Dodiya','Motor Policy','2021-08- 
10','2022-08-09',9600,'9601629656')
Insert Into CustomerData Values(9,'K001','Karina Shah','Health Policy','2021-08- 
06','2022-08-05',2500,'9911629656')  
Insert Into CustomerData Values(10,'S001','Sneha Mer','Motor Policy','2021-08-26','2022- 
08-25',3600,'8866554466')
Insert Into CustomerData Values(11,'U001','Uday Dodiya','PA Policy','2021-08-20','2022- 
08-19',3500,'9601629656')

Here

Desired Output

enter image description here

In Above Output You See H001 has 01-08-2022 So they display first after K001 Has Also 01-08-2022 Than U001 has also 01-08-2022 and than Z001 has 15-08-2022 And S001 has 25-08-2022

And All Group Data Also In Sorted Internally.

Sort the groups by each group's minimum ending date, and then the items in the group by their ending date

Anyone Please Help In this

Thank You In Advance

2 Answers

The basic syntax used for writing the SELECT query with ORDER BY clause is as follows:

SELECT * FROM
CustomerData
ORDER BY EndDate ASC | DESC;

Ok, now I understood. You want to sort the groups by each group's minimum starting date, and then the items in the group by their starting date. So what you need is a subquery like this one:

SELECT * from CustomerData cust
    INNER JOIN
        (SELECT GroupId, MIN(StartDate) GroupStart from CustomerData
            GROUP BY GroupId) custgroup
        ON cust.GroupId = custgroup.GroupId
   ORDER BY custgroup.GroupStart, cust.StartDate
Related