SELECT --COUNT(DIFF) Count(DATEDIFF(D, MinDate, MaxDate)/30) AS DIFF FROM ( SELECT MAX(TDate) AS MaxDate, MIN(TDate) AS MinDate FROM EDATA GROUP BY TCard )a Group by DATEDIFF(D, MinDate, MaxDate)/30Now i want to apply some kind of sorting in this query before performing DateDiff operation (sorting can be based on several parameters like age, name etc. but 1 at a time according to the cases)Now I want to know How to apply cases over this query an where?