patternsqlMinor
T-SQL Update with Max and Min value from another table
Viewed 0 times
updatesqlwithvalueminmaxanotherandfromtable
Problem
I don't have much experience with SQL queries and I'm trying to learn and understand from my mistakes.
I have two tables:
And I'm trying to update the columm
But it updated both columns with value 4. I've also tried using
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?
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.Number1,t1.Number, t2.MinNo)
FROM #TempTest2 t2
JOIN #TempTest t1 ON t2.Id=t1.IdBut it updated both columns with value 4. I've also tried using
BEGIN Transaction
...
COMMITaround the update, but the result is the same.
What am I doing wrong?
What is the best approach to update the second table correctly?
Solution
For
For
The query will look something like this:
output:
Id
MaxNo
MinNo
1
7
3
dbfiddle
MinNo with the minimum bigger than 1 = will ignor(mark as null) all the records smaller or equal to 1.CASE WHEN Number <=1 THEN NULL ELSE Number ENDFor
max number smaller than 8 = will ignor(mark as null) all the records greater or equal to 8.CASE WHEN Number >= 8 THEN NULL ELSE Number ENDThe query will look something like this:
UPDATE t2
SET MaxNo = t1.MaxNo,
MinNo = t1.MinNo
FROM
#TempTest2 as t2
INNER JOIN
(
SELECT id,
MinNo = MIN(CASE WHEN Number = 8 THEN NULL ELSE Number END)
FROM
#TempTest
GROUP BY
id
)as t1
ON t2.Id = t1.Id;
SELECT *
FROM #TempTest2;output:
Id
MaxNo
MinNo
1
7
3
dbfiddle
Code Snippets
CASE WHEN Number <=1 THEN NULL ELSE Number ENDCASE WHEN Number >= 8 THEN NULL ELSE Number ENDUPDATE t2
SET MaxNo = t1.MaxNo,
MinNo = t1.MinNo
FROM
#TempTest2 as t2
INNER JOIN
(
SELECT id,
MinNo = MIN(CASE WHEN Number <=1 THEN NULL ELSE Number END),
MaxNo = MAX(CASE WHEN Number >= 8 THEN NULL ELSE Number END)
FROM
#TempTest
GROUP BY
id
)as t1
ON t2.Id = t1.Id;
SELECT *
FROM #TempTest2;Context
StackExchange Database Administrators Q#315212, answer score: 4
Revisions (0)
No revisions yet.