简体   繁体   中英

SQL Server update a cell to show duplicates

I have a table displaying some scanned barcodes . Each barcode has its own ID, and we will link all the barcodes scanned together using a foreign key we call scanHeaderID that will have the same scanHeaderID for each scan imported. I want to add a column to show whether the row is a duplicate within the same for those value with the same scanHeaderID . Like so

ScanID | ScanHeaderID | Barcode | Duplicate
-------+--------------+---------+-------
 1     | 1            | 1111    | false
 2     | 1            | 2222    | true
 3     | 1            | 2222    | true
 4     | 1            | 3333    | false
 5     | 2            | 1111    | false
 6     | 2            | 5555    | false

ScanID 2 and 3 are marked as duplicate since they contain they same barcode in the same ScanHeaderID . I need to add this column to a preexisting table and update the table to display these values for Scans that already exist. I need to write SQL that will go through each row, and update the duplicate column base on this criteria. I am not sure where to start. Any help would be greatly appreciated. Thanks in advance.

Once option is to use the window functions

Example

Select *
      ,Duplicate = case when sum(1) over (Partition By ScanHeaderID,BarCode)>1 then 'true' else 'false' end
 From  YourTable

Returns

ScanID  ScanHeaderID    Barcode Dupicate
1       1               1111    false
2       1               2222    true
3       1               2222    true
4       1               3333    false
5       2               1111    false
6       2               5555    false

Edit - For the Update

;with cte as ( 
    Select *
          ,NewVal = case when sum(1) over (Partition By ScanHeaderID,BarCode)>1 then 'true' else 'false' end
    From YourTable
)
Update cte Set Duplicate=NewVal

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM