Bhupinder Singh
Bhupinder Singh

Reputation: 1071

SQL SERVER : populating a column based on other other columns

I have a tableA: (ID int, matchPID char,PID char, set int, num char, QID char, QStatus char)

ID matchPID   PID    set  num   QID  QStatus 
1  00001230   xx123   1   234  
2  00001229   xx234   1   214
3  00000054   xx654   1   NULL
4  00012000   xx125   2   
5  00A53214   xx321   2   
6  00000100   xx213   2

matchPID is always (00-xxxxxx) x can be char or int.

now I have to populate OID just one value for each set according to [num].

  1. If for any set, there exists any value in [num], then populate OID with PID where exists [num] for same set and populate Qstatus = 'fail' in rest.

so OID can be populated in id 1 or 2. (any1), then check lowest matchPID and populate here. so in this case (set1) expected result is :

ID matchPID   PID    set  num   QID       QStatus 

1  00001230   xx123   1   234   NULL       FAIL
2  00001229   xx234   1   214   xx234      NULL
3  00000054   xx654   1   NULL  NULL       FAIL
  1. if for any set there isnt any [num] found, then pick lowest matchPID and populate QID with PID and fail the rest.

notice that matchPID starts with 00 and then it can be 0>1>2>..>A>B>C>.... so expected result for set2 is :

ID matchPID   PID    set  num   QID       QStatus

4  00012000   xx125   2   NULL  NULL      FAIL
5  00A53214   xx321   2   NULL  NULL      FAIL
6  00000100   xx213   2   NULL  xx213     NULL

Thanks

Upvotes: 0

Views: 1881

Answers (1)

GilM
GilM

Reputation: 3761

Did you want something like this?:

;WITH setInfo AS (
SELECT [SET], 
    CASE WHEN EXISTS (SELECT 1 FROM tableA b 
                                WHERE b.[set]=a.[set] AND num IS NOT NULL) 
                                THEN 1 ELSE 0 END AS HasNum,
    MIN(matchPID) AS MinMatchPID
FROM tableA a
GROUP BY [SET]
)
UPDATE a SET
QID = CASE WHEN s.HasNum = 0 AND a.matchPID = s.MinMatchPID THEN a.PID
           WHEN s.HasNum = 0 AND a.matchPID != s.MinMatchPID THEN NULL
           WHEN s.HasNum = 1 AND a.matchPID = (SELECT min(matchpid) FROM tableA b
                                     WHERE b.[set] = a.[set]
                                     AND b.num is not null
                                      ) 
                                     THEN a.PID
           ELSE NULL
           END,
QStatus = CASE WHEN s.HasNum = 0 AND a.matchPID = s.MinMatchPID THEN NULL
           WHEN s.HasNum = 0 AND a.matchPID != s.MinMatchPID THEN 'FAIL'
           WHEN s.HasNum = 1 AND a.matchPID = (SELECT min(matchpid) FROM tableA b
                                     WHERE b.[set] = a.[set]
                                     AND b.num is not null
                                      ) 
                                     THEN a.PID
           ELSE 'FAIL'
           END
FROM tableA a
JOIN setInfo s ON s.[set] = a.[set]

Upvotes: 1

Related Questions