简体   繁体   English

SQL Server查询合并1中的2行

[英]SQL Server query for merging 2 rows in 1

There is a SQL Server table (see the screenshot below) that I cannot change: 有一个我无法更改的SQL Server表(请参见下面的屏幕快照):

实际表

Products have identifiers and process parameters. 产品具有标识符和过程参数。 There are 2 processes, A and B. Every process stores data in an own row. 有两个进程,A和B。每个进程将数据存储在自己的行中。

I would like to get a table result without useless NULL values. 我想要一个没有无用NULL值的表结果。 One product on one row, no more. 一种产品排在一行,没有更多。 Desired cells are highlighted. 所需的单元格突出显示。 See the 2nd screenshot for the desired output: 请参阅第二个屏幕截图以获取所需的输出:

所需的输出

select a.id,
       isnull(b.state,   a.state)   as state,
       isnull(b.process, a.process) as process,
       isnull(b.length,  a.length)  as length,
       isnull(b.force,   a.force)   as force,
       isnull(b.angle,   a.angle)   as angle
 from      table as a 
 left join table as b 
   on a.id = b.id   
  and b.process = 'B'
where a.process = 'A' 


DECLARE @T AS TABLE (id int, state varchar(10), process varchar(10), length int, angle int  
                     primary key (id, process));
insert into @t (id, state, process, length, angle)  values
      (111, 'OK',  'A', 77, null)
     ,(111, 'OK',  'B', null, 30)
     ,(159, 'NOK', 'A', 89, null)
     ,(147, 'OK',  'A', 78, null)
     ,(147, 'NOK', 'B', null, 36);

select ta.id, --ta.*, tb.*
       isnull(tb.state,   ta.state)   as state,
       isnull(tb.process, ta.process) as process,
       isnull(tb.length,  ta.length)  as length, 
       isnull(tb.angle,   ta.angle)   as angle
 from @t ta 
 left join @t tb 
   on ta.id = tb.id   
  and tb.process = 'B' 
where ta.process = 'A' 
order by ta.id 

Self join? 自我加入? (edited) (编辑)

so, 所以,

select
 a.id,
 a.process,
 isnull(a.length, b.length) as length,
 isnull(a.force, b.force) as force,
 isnull(a.angle, b.angle) as angle
from
 (select * from tmpdel where process = 'A') as a left join
 (select * from tmpdel where process = 'B') as b on
 a.id = b.id

I've given this a quick test and I think it looks right. 我已经对此进行了快速测试,我认为它看起来不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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