用于将父对象的值提取到子对象的SQL查询
我有两张表,用于将父对象的值提取到子对象的SQL查询,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有两张表,ITEM和TARIF。在tarif表中,我有父项和一些子项的价格。现在,我必须通过将TARIF表连接到ITEM表来获取父项的价格。在tarif表中,某些父级将不在那个里,但在加入时,它正在为父级和子级创建一行“NULL”值。如果父项在TARIF表中不存在,我不想导出这些项 项目表格 status item_code ga_article ----------------------------- Parent1 1234 1234 X child1 1234
ITEM
和TARIF
。在tarif表中,我有父项和一些子项的价格。现在,我必须通过将TARIF
表连接到ITEM
表来获取父项的价格。在tarif表中,某些父级将不在那个里,但在加入时,它正在为父级和子级创建一行“NULL”值。如果父项在TARIF
表中不存在,我不想导出这些项
项目
表格
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
item_code gf_article price
----------------------------
1234 1234 X 100
2345 2345 X 150
2345 2345 01 X 200
tarif
表格
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
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 <> ''
您可以将查询结束为
from article a
join tarif t on t.item_code = a.item_code
因此,将下面的内容用作通过item\u 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
请试试这个
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
可能使用
内部联接
而不是左联接
?在where子句->金额不为空的情况下再添加一个条件如果我使用内部联接,我无法将家长价格带给孩子谢谢Marc_s,Sahi回答我