SQL: 根据组参数查询设置值

SQL: Query to set value based on group parameter

我需要帮助编写查询以在我的数据库中的 table 上执行以下操作:

Select all rows where the values in Column1 are the same
    If a 'Primary' has not been set in Column2 for any of them
        Set Column2 = 'Primary' for first row in the group 
    Else go on to the next group 

要点:我每组只能有一个'Primary'标签

示例输入:

Column1 | Column2 | 
ID1                 
ID1                       
ID1                     
ID2       Primary
ID2       
ID3       
ID3       

示例结果:

Column1 | Column2 | 
ID1       Primary         
ID1                       
ID1                     
ID2       Primary
ID2       
ID3       Primary   
ID3       

谢谢!

SELECT Column1  
     ,CASE 
        WHEN ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [TargetColumn]) = 1 
          THEN  'Primary' 
          ELSE '' 
     END AS Column2
FROM TableName

TargetColumn 将是将在每组 Column1 中决定哪个值是主值的列。

使用ROW_NUMER window 函数查找每组的第一条记录,然后仅更新在column2

中没有primary 值的记录

由于没有可用的列来查找每组的第一条记录,我在 order by

中使用了 (select null)

示例数据

CREATE TABLE #ee(Column1 VARCHAR(50),Column2 VARCHAR(50))

INSERT #ee
VALUES ('ID1',NULL),
       ('ID1',NULL),
       ('ID1',NULL),
       ('ID2','Primary'),
       ('ID2',NULL),
       ('ID3',NULL),
       ('ID3',NULL) 

更新查询:

;WITH cte
     AS (SELECT *,
                Row_number()OVER(partition BY column1 ORDER BY (SELECT NULL)) RN
         FROM   #ee a
         WHERE  NOT EXISTS (SELECT 1
                            FROM   #ee b
                            WHERE  a.Column1 = b.Column1
                                   AND b.Column2 = 'primary'))
UPDATE cte
SET    Column2 = 'primary'
WHERE  rn = 1 

结果:

Column1 Column2
------- -------
ID1     primary
ID1     NULL
ID1     NULL
ID2     Primary
ID2     NULL
ID3     primary
ID3     NULL