I want to find the minimum value for a given row in a SQL table (where all values in the table other than the column names are integers), with only inputting the column names in one location.
In this example, Column_Names are = A, B, C, D, and E
Screenshot of Sample Table, where minimums are (7, 1, 11)
I got to a point where I can run this code and get the values for a given row. These values are stored in a temporary table, #Test
, and the minimum value in #Test
is stored in another temporary table, #Answers
. I then use a While
loop with a running counter to iterate through all the rows and find the minimum's of the rows. The list of minimums are in the temporary table, #Answers
.
CREATE TABLE #Test (Calc INT);
CREATE TABLE #Answers (Minimum INT);
DECLARE @Counter INT
SET @Counter = 1
WHILE (@Counter <= (SELECT COUNT(Counter_Name) FROM #Data))
BEGIN
INSERT INTO #Test
SELECT A
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
INSERT INTO #Test
SELECT B
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
INSERT INTO #Test
SELECT C
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
INSERT INTO #Test
SELECT D
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
INSERT INTO #Test
SELECT E
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
INSERT INTO #Answers
SELECT min(Calc) FROM #Test
DROP TABLE #Test
CREATE TABLE #Test (Calc INT);
SET @Counter = @Counter + 1
How can I run this code for a table with n
number of columns? How do I generalize this code, or at the very least make it so that I don't have to copy & paste this whole piece of code for every column.:
INSERT INTO #Test
SELECT Counter_Name
FROM (SELECT ROW_NUMBER () OVER (ORDER BY (SELECT NULL)) AS RowNum, * FROM #Data) sub
WHERE
RowNum = @Counter
The ideal solution would be storing column names in an array and then iterate through that array using the above code. I have been unable to write up a working script for this step.