We'll take this in steps. Here's the data setup:
DECLARE @table TABLE
(
ID INTEGER NOT NULL
,Date DATETIME NOT NULL
,ColX INTEGER NOT NULL
,ColY INTEGER NOT NULL
,ColZ INTEGER NOT NULL
);
INSERT INTO @table
(ID,Date,ColX,ColY,ColZ)
VALUES
(79185673, '2018-11-28T00:00:00', 3, 5, 7);
INSERT INTO @table
(ID,Date,ColX,ColY,ColZ)
VALUES
(79185673, '2018-12-02T00:00:00', 2, 4, 6);
INSERT INTO @table
(ID,Date,ColX,ColY,ColZ)
VALUES
(79185673, '2018-12-04T00:00:00', 4, 5, 6);
First, we'll find the record with the maximum date.
SELECT TOP (1)
*
FROM
@table
ORDER BY
[Date] DESC
+----------+-------------------------+------+------+------+
| ID | Date | ColX | ColY | ColZ |
+----------+-------------------------+------+------+------+
| 79185673 | 2018-12-04 00:00:00.000 | 4 | 5 | 6 |
+----------+-------------------------+------+------+------+
So that forms our base data set. From there, we want to UNPIVOT
to get all of the column values into a single column. You'll have to type out all of the other column names in the UNPIVOT
, but you can probably get SSMS to do some of that scripting for you by just using a default SELECT TOP N ROWS
query and copying and pasting the column names from there.
SELECT
*
FROM
(
SELECT
TOP (1)
*
FROM
@table
ORDER BY
[Date] DESC
) AS d
UNPIVOT
(
Nums
FOR ColName IN (ColX, ColY, ColZ)
) AS p
+----------+-------------------------+------+---------+
| ID | Date | Nums | ColName |
+----------+-------------------------+------+---------+
| 79185673 | 2018-12-04 00:00:00.000 | 4 | ColX |
| 79185673 | 2018-12-04 00:00:00.000 | 5 | ColY |
| 79185673 | 2018-12-04 00:00:00.000 | 6 | ColZ |
+----------+-------------------------+------+---------+
According to the comments, the numbers are always increasing across the columns, so we can sort by them safely and maintain the original order. But we only care about numbers that are smaller than the target number, 5.4 in this example. So that's our WHERE
clause. And we want the largest number that's less than 5.4, so we'll be using a descending ORDER BY
clause. We only want that single value, so we only need the TOP (1)
in our final results.
DECLARE @target DECIMAL(5,1) = 5.4;
SELECT TOP (1)
*
FROM
(
SELECT
TOP (1)
*
FROM
@table
ORDER BY
[Date] DESC
) AS d
UNPIVOT
(
Nums
FOR ColName IN (ColX, ColY, ColZ)
) AS p
WHERE
p.Nums < @target
ORDER BY
p.Nums DESC;
+----------+-------------------------+------+---------+
| ID | Date | Nums | ColName |
+----------+-------------------------+------+---------+
| 79185673 | 2018-12-04 00:00:00.000 | 5 | ColY |
+----------+-------------------------+------+---------+