繁体   English   中英

SQL Server查询合并1中的2行

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

有一个我无法更改的SQL Server表(请参见下面的屏幕快照):

实际表

产品具有标识符和过程参数。 有两个进程,A和B。每个进程将数据存储在自己的行中。

我想要一个没有无用NULL值的表结果。 一种产品排在一行,没有更多。 所需的单元格突出显示。 请参阅第二个屏幕截图以获取所需的输出:

所需的输出

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 

自我加入? (编辑)

所以,

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

我已经对此进行了快速测试,我认为它看起来不错。

暂无
暂无

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

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