简体   繁体   中英

Is there a way to join 2 records from same table in SQL

Already found!!!

join ItemUom k on k.Item = Item.Oid and k.ItemUomId = 'Krat'    
etc ... 

Is there a way to join/link some fields of 2 different records of same table? See picture for example of data structure. Can I give the results of the joins a name, so I can get fields from those?

I want something like:

select  Item.ItemId, 
        Item.Description,
        ItemUom'Krat'.ItemUomId,
        ItemUom'Krat'.ContentQty,
        ItemUom'Stuks'.ItemUomId,
        ItemUom'Stuks'.ContentQty,
from Item
join ItemUom 'Krat' on ItemUom.Item = Item.Oid and ItemUomId = 'Krat' 
join ItemUom 'Stuks' on ItemUom.Item = Item.Oid and ItemUomId = 'Stuks'

数据结构示例

Do not use single quotes for aliases. But your query has many other issues.

If I understand correctly, you want to join the tables and can then use conditional aggregation for the "pivoting" that you want to do.

I think this does what you want:

select i.ItemId, i.Description,
       max(case when iu.ItemUomId = 'Krat' then iu.ItemUomId end),
       max(case when iu.ItemUomId = 'Krat' then iu.ContentQty end),
       max(case when iu.ItemUomId = 'Stuks' then iu.ItemUomId end),
       max(case when iu.ItemUomId = 'Stuks' then iu.ContentQty end)
from ItemUom iu join
     Item ik
     on iu.Item = i.Oid 
group by i.ItemId, i.Description

EDIT:

Actually, the following produces the same output, but I think it is the approach you are trying to take:

select i.ItemId, i.Description,
       ik.ItemUomId, ik.ContentQty,
       ist.ItemUomId, ist.ContentQty
from Item i join
     ItemUom ik
     on ik.Item = i.Oid and
        ik.ItemUomId = 'Krat' join
      ItemUom ist
      on ist.Item = i.Oid and 
         ist.ItemUomId = 'Stuks';

Note the use of table aliases. And single quotes are ONLY used for strings, not for column or table aliases.

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