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

时间:2019-03-26 06:22:32

标签: sql sql-server tsql

我有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

现在,当我将TARIF加入Item表以获取价格时

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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