SQL查询以获取父级到子级的值

问题描述 投票:1回答:2

我有2张桌子,ITEMTARIF。在tarif表中我有父项和一些孩子的价格。现在我必须通过将TARIF表连接到ITEM表来获取其子项的父级价格。在tarif表中,某些父级将不在那里,但在加入时,它正在为父级和子级创建一个“NULL”值的行。如果TARIF表中不存在父项,我不想导出项目。

Item

status  item_code ga_article
-----------------------------
Parent1 1234      1234   X
child1  1234      1234 01 x
child2  1234      1234 02 x
parent2 2345      2345   X
child21 2345      2345 01 X
child22 2345      2345 02 x
parent3 3456      3456  X
child31 3456      3456 01 X

tarif

item_code gf_article  price
----------------------------
1234      1234  X     100
2345      2345  X     150
2345      2345 01 X   200

现在,当我加入TARIFItem表来获得价格

select 
    ga_article,
    case 
       when t.price is null and i.ga_article like i.item_code +'X%' 
          then (select top(1) price from tarif 
                where GF_ARTICLE like item-code + '%' ) 
          else price
    end as amount
from 
    article
left join 
    TARIF on gf_article = ga_article 

我的输出是:

ga_article  amount
-------------------
1234  X      100
1234 01 x    100
1234 02 x    100
2345  X      150
2345 01 x    200
2345 02 x    150
3456  X      null
3456 01 x    null

我不想看到最后两行的空值

SELECT
    CASE 
       WHEN GF_PRIXUNITAIRE IS NULL
            AND ga_article LIKE ga_Codearticle + '%X' 
          THEN (SELECT TOP(1) GF_PRIXUNITAIRE FROM tarif 
                WHERE GF_ARTICLE LIKE ga_Codearticle + '%' 
                  AND GF_DEVISE='QAR' ) 
          ELSE GF_PRIXUNITAIRE
    END AS price
FROM  
    Article A 
LEFT JOIN 
    tarif L ON gf_article = GA_ARTICLE 
            AND GF_DEVISE = 'QAR' 
            AND GF_REGIMEPRIX = 'TTC' 
WHERE
    GA_STATUTART <> 'UNI' AND GA_CODEARTICLE <> ''

我的预期输出是:

ga_article  amount
---------------------
1234  X      100
1234 01 x    100
1234 02 x    100
2345  X      150
2345 01 x    200
2345 02 x    150
sql sql-server tsql
2个回答
1
投票

请试试这个

SELECT * FROM
(select ga_article,
case when t.price is null and i.ga_article like i.item_code +'X%' then(SELECT TOP(1) price FROM tarif WHERE GF_ARTICLE like item-code+ '%' ) 
else price
end as amount
from article
left join TARIF on gf_article = ga_article ) AS A WHERE A.amount IS NOT NULL

0
投票

您最终可以查询

from article a
join tarif t on t.item_code = a.item_code

因此,使用下面的item_code列连接内连接

select ga_article,
       case
         when t.price is null and i.ga_article like i.item_code + 'X%' then
          (SELECT TOP(1) price
             FROM tarif
            WHERE GF_ARTICLE like item - code + '%')
         else
          price
       end as amount
  from article a
  join tarif t on t.item_code = a.item_code
© www.soinside.com 2019 - 2024. All rights reserved.