SQL SERVER:根据其他其他列填充列

时间:2011-10-18 21:19:23

标签: sql-server tsql

我有一个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始终为(00-xxxxxx)x可以是char或int。

现在我必须根据[num]为每个集合填充OID一个值。

  1. 如果对于任何集合,[num]中存在任何值,则使用PID填充OID,其中对于相同的集合存在[num]并在休息时填充Qstatus ='fail'。
  2. 因此可以在id 1或2(any1)中填充OID,然后检查最低的matchPID并填充此处。所以在这种情况下(set1)预期的结果是:

    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. 如果对于任何集合没有找到任何[num],则选择最低的matchPID并用PID填充QID并使其余部分失败。
    2. 注意matchPID以00开头,然后它可以是0> 1> 2> ...> A> B> C> .... 所以set2的预期结果是:

      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
      

      由于

1 个答案:

答案 0 :(得分:1)

你想要这样的东西吗?:

;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]