繁体   English   中英

SQL Server-如何从同一行的不同行中选择值

[英]SQL Server - How to SELECT values from different rows but in the same table

例如,我有一个名为tb_Item的表

----------------------------------
|Item_Ref|Main_Item_Ref|Type|Rate|
|--------+-------------+----+----|
|1234ABC |MNJDH        |Sub |0   |
|MNJDH   |MNJDH        |Main|98  |
----------------------------------

基本上,我要实现的是获取Main项目的Rate值并将其放在Sub Item / s上。

在此样本表中,项1234ABC如何从其主项MNJDH中获得98速率并返回行,如下所示:

----------------------------------
|Item_Ref|Main_Item_Ref|Type|Rate|
|--------+-------------+----+----|
|1234ABC |MNJDH        |Sub |98  |
----------------------------------

谢谢。

您可以使用自我加入来做到这一点:

select i.*, m.Rate
from tb_item i left join
     tb_item m
     on i.main_item_ref = m.main_item_ref and
        m.type = 'Main'
where i.type = 'Sub';

自我内在联系

 select t1.Item_Ref, t1.Main_Item_ref, t1.type,t2.Rate
  from #temptable t1
  inner join #temptable t2 
    on t1.Main_Item_ref = t2.Main_Item_ref 
    and t2.type = 'Main'
    and t1.type ='Sub'

暂无
暂无

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

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