Need SQL to disconnect rows

时间:2016-04-07 10:48:16

标签: sql sql-server sql-server-2012

The header is a bit vague but I try to explain I have 2 tables OrderPartyRole and PriceRequest.

In the past there was one to many relation.One orderpartyrole could have many pricerequests. This is now changed so it can only have 0 or 1 pricerequest in the model.

But problem is historical data in database. There many rows of Pricerequest that point to the same OrderpartyRole. According the new rules only one is allowed.

I used this SQL to verify this

SELECT Max(pricerequest.orderPartyRole) AS partyrole_Max,
       Min(pricerequest.orderPartyRole) AS partyrole_Min
FROM   orderpartyrole, 
       pricerequest 
WHERE  orderpartyrole.bold_id = pricerequest.orderpartyrole 
GROUP  BY orderpartyrole 
HAVING Count(*) > 1 

It return 3287 rows, but ideally this should be 0.

So my concrete question is this. What condition should I use to set pricerequest.orderPartyRole to be -1 on those cases. Like this

UPDATE pricerequest 
SET    pricerequest.orderpartyrole = -1 
FROM   pricerequest 
WHERE  <Some condition>

The important thing here is that the SQL should not write -1 to all. It should leave one.

A concrete example

SELECT bold_id, orderpartyrole, remark 
FROM   pricerequest 
WHERE  orderpartyrole = 76321050 

The result is

BOLD_ID orderPartyRole  Remark
76322590    76321050    
76964885    76321050    ok att använda export priser?

In this case I would choose to set OrderpartyRole = -1 as remark is blank using

UPDATE pricerequest 
SET    pricerequest.orderpartyrole = -1 
FROM   pricerequest 
WHERE  Bold_id = 76322590   

And leave the other row as is.

Model

1 个答案:

答案 0 :(得分:1)

You can use row_number() for this . . . assuming you have no other columns to define uniqueness (such as a date or identity column):

WITH toupdate as (
      SELECT pr.*,
             ROW_NUMBER() OVER (PARTITION BY orderpartyrole 
                                ORDER BY CASE WHEN Remark > '' 
                                              THEN 0
                                              ELSE 1 
                                         END, 
                                         Bold_id DESC) as seqnum
      FROM pricerequest pr
     )
UPDATE toupdate
    SET orderpartyrole = -1
    WHERE seqnum > 1;