I don't have much experience with SQL queries and I'm trying to learn and understand from my mistakes. I have two tables:
CREATE TABLE #TempTest
(Id INT,
Number INT)
CREATE TABLE #TempTest2
(Id INT,
MaxNo INT,
MinNo INT)
INSERT INTO #TempTest VALUES (1,4)
INSERT INTO #TempTest VALUES (1,6)
INSERT INTO #TempTest VALUES (1,9)
INSERT INTO #TempTest VALUES (1,7)
INSERT INTO #TempTest VALUES (1,3)
INSERT INTO #TempTest VALUES (1,1)
INSERT INTO #TempTest VALUES (1,5)
INSERT INTO #TempTest2 VALUES (1,0,10)
And I'm trying to update the columm MaxNo
with the max number smaller than 8 from the first table and MinNo
with the minimum bigger than 1:
UPDATE t2
SET MaxNo = IIF(t1.Number>t2.MaxNo AND t1.Number<8,t1.Number, t2.MaxNo),
MinNo = IIF(t1.Number<t2.MinNo AND t1.Number>1,t1.Number, t2.MinNo)
FROM #TempTest2 t2
JOIN #TempTest t1 ON t2.Id=t1.Id
But it updated both columns with value 4. I've also tried using
BEGIN Transaction
...
COMMIT
around the update, but the result is the same.
What am I doing wrong? What is the best approach to update the second table correctly?