CREATE TABLE test
(
sts_id int
, [status1] int
, [status2] int
, [status3] int
, [status4] int
)
INSERT INTO test values
('1','999','0','0','0'),
('1','100','0','0','0'),
('2','200','999','0','0'),
('3','500','600','999','0'),
('4','200','700','900','998'),
('4','300','400','800','999')
In SQL Server (2016), I have a query for the above table to get the highest value <= 900 (if possible)
SELECT DISTINCT
sts_id
, CASE
WHEN status1 > 0 AND status2 = 0 THEN status1
WHEN status2 > 900 AND status3 = 0 THEN status1
WHEN status2 BETWEEN 1 AND 900 AND status3 = 0 THEN status2
WHEN status3 > 900 AND status4 = 0 THEN status2
WHEN status3 BETWEEN 1 AND 900 AND status4 = 0 THEN status3
WHEN status4 > 900 THEN status3 WHEN status4 BETWEEN 1 AND 900 THEN status4
ELSE status1
END AS 'status'
FROM test
Giving me this:
| sts_ID | status |
|--------|--------|
| 1 | 100 |
| 1 | 999 |
| 2 | 200 |
| 3 | 600 |
| 4 | 800 |
| 4 | 900 |
I then join this onto another table on the sts_id, and get the max(status) value.
However, I am not concerned with statuses above 900, and sts_id 1 for example is going to give me 999, even though I would prefer it to give me 100.
Is there any way I can incorporate some kind of CASE to get the next value if there is one available for a single ID? Would dense_rank() possibly help?