简体   繁体   中英

Part Id 3900 take wrong technology id as 7 and it must Be 2 because Feature Name and Value Exist?

I work on sql server 2017 I have table #partsfeature already exist as below

create table #partsfeature
  (
  PartId int,
  FeatureName varchar(300),
  FeatureValue varchar(300),
  TechnologyId int
  )
   insert into #partsfeature(PartId,FeatureName,FeatureValue,TechnologyId)
   values
   (1211,'AC','5V',1),
   (2421,'grail','51V',2),
   (6211,'compress','33v',3)

my issue Done For Part id 3900 it take wrong

Technology Id 7 and Correct Must be 2

Because Feature name and Feature Value Exist

So it Must Take Same TechnologyId Exist

on Table #partsfeature as Technology Id 2 .

correct will be as Below

   +--------+--------------+---------------+-------------
    | PartID |  FeatureName |  FeatureValue | TechnologyId   
    +--------+--------------+---------------+-------------
    |   3900 | grail        | 51V           |   2
    +--------+--------------+---------------+-------

what I try is

 insert into #partsfeature(PartId,FeatureName,FeatureValue,TechnologyId)
select  PartId,FeatureName,FeatureValue,
        TechnologyId  = dense_rank() over (order by FeatureName,FeatureValue)
                      + (select max(TechnologyId) from #partsfeature)
from    
(
        values
        (3900,'grail','51V',NULL),
        (5442,'compress','30v',NULL),
        (7791,'AC','59V',NULL),
        (8321,'Angit','50V',NULL)
) s (PartId,FeatureName,FeatureValue,TechnologyId)

Expected Result For Parts Inserted之前存在错误的数据技术 ID

Use NOT EXISTS() to check for existance of FeatureName and FeatureValue . Sub query to get existing maximum TechnologyId from table and row_number() to generate a running sequence

insert into #partsfeature(PartId,FeatureName,FeatureValue,TechnologyId)
select  PartId,FeatureName,FeatureValue,
        TechnologyId  = row_number() over (order by PartId)
                      + (select max(TechnologyId) from #partsfeature)
from    
(
        values
        (3900,'grail','51V',NULL),
        (5442,'compress','30v',NULL),
        (7791,'AC','59V',NULL),
        (8321,'Angit','50V',NULL)
) s (PartId,FeatureName,FeatureValue,TechnologyId)
where   not exists
        (
            select  *
            from    #partsfeature x
            where   x.FeatureName   = s.FeatureName
            and     x.FeatureValue  = s.FeatureValue
        )

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