Skip to content
Advertisement

Get the all unique permutation and combinations of ‘where clause conditions’ for my table in SQL Server

I would like to see all possible unique scenarios of my data in a table.

    Mode    StartDate               EndDate
------------------------------------------------
0       1/1/2018                1/12/2018
0       1/5/2015                1/12/2018
0       3/8/2015                1/12/2019
0       1/1/2020                1/1/2020
0       5/5/2015                5/5/2015
1       1/1/2018                5/5/2015
1       5/8/1947                9/9/1902
1       4/4/2014                3/3/2013
1       1/4/2020                1/1/2001
1       3/8/2015                1/12/2019
1       19/11/1992              19/11/1992

I can give the Input like

Operators=[<,>,=,……] Operands=[mode, StartDate,EndDate,…..]

I am expecting the result like

0 and 1/1/2018<1/12/2018 0 and 1/1/2020=1/1/2020 1 and 1/1/2018>5/5/2015 1 and 3/8/2015<1/12/2019 1 and 19/11/1992=19/11/1992

these are my unique patterns in my data. So is there any query or java program to get these unique patterns of my data so that I can test my application with all possible scenarios.

Note: I am having a total of 6 six columns in my table. for sample purposes, I only gave 3 columns.

Advertisement

Answer

You can do that by generalizing the data into categories using window function and pick one from each set. try the following:

;with cte as 
(
    select Mode, StartDate, EndDate, ROW_NUMBER() over (partition by Mode, case when CONVERT(date, StartDate, 103) < CONVERT(date, EndDate, 103) then 0 when CONVERT(date, StartDate, 103) = CONVERT(date, EndDate, 103) then 1 else 2 end order by Mode) rn
    from @tab
)

select Mode, StartDate, EndDate from cte 
where rn = 1
order by Mode,  CONVERT(date, StartDate, 103)

Please see db<>fiddle here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement