I need help writing a query to do the following on a table in my DB:
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
Key points: I can only have one 'Primary' tag per group
Sample input:
Column1 | Column2 |
ID1
ID1
ID1
ID2 Primary
ID2
ID3
ID3
Sample Result:
Column1 | Column2 |
ID1 Primary
ID1
ID1
ID2 Primary
ID2
ID3 Primary
ID3
Thank you!
SELECT Column1
,CASE
WHEN ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY [TargetColumn]) = 1
THEN 'Primary'
ELSE ''
END AS Column2
FROM TableName
TargetColumn
will be the column that will decide in each group of Column1 which Value is the Primary Value.
Use ROW_NUMER
window function to find the first record per group then update only the records which doesnot have primary
value in column2
Since there is no column available to find the first record per group i have used (select null)
in order by
Sample data
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)
Update query:
;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
Result:
Column1 Column2
------- -------
ID1 primary
ID1 NULL
ID1 NULL
ID2 Primary
ID2 NULL
ID3 primary
ID3 NULL
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.