相同表的子查询

时间:2019-01-15 10:33:17

标签: sql subquery

我有一个包含以下内容的表:

  • ID_Magasin:捕鲸场为001,magasin1为c01,magasin 2为c02,..
  • Qte_Physique:商品的数量编号
  • id_article:代码文章
  • lib_article:文章名称

我首先要查询,为每个magasin带来所有文章数量。 其次,在同一查询中,我想添加一个新列以显示数据仓库中同一商品的数量。

2 个答案:

答案 0 :(得分:0)

如果我理解正确,则可以使用窗口功能来做到这一点:

select d.*
from (select d.*, 
            sum(case when id_magasin = '001' then Qte_Physique else 0 end) over (partition by id_article) as wharehouse_qte
     from dispo d
    ) d
where id_magasin <> '001';

答案 1 :(得分:0)

您的子查询与主查询不相关。即缺少要看哪种产品的条件。

select
  gq_depot,
  gq_article,
  gq_physique,
  (
    select warehouse.gq_physique
    from dispo warehouse
    where warehouse.gq_depot = '001'
    and warehouse.gq_article = magasin.gq_article
  ) as wh_physique
from dispo magasin
where gq_depot <> '001'
order by gq_depot, gq_article;

您可以对联接执行相同的操作:

select
  magasin.gq_depot,
  magasin.gq_article,
  magasin.gq_physique,
  warehouse.gq_physique as wh_physique
from dispo magasin
left join dispo warehouse on  warehouse.gq_article = magasin.gq_article
                          and warehouse.gq_depot = '001'
where magasin.gq_depot <> '001'
order by magasin.gq_depot, magasin.gq_article;

出于可读性考虑,如果DBMS具有以下子句,则可以使用WITH子句:

with warehouse as (select * from dispo where gq_depot = '001')
   , magasin as (select * from dispo where gq_depot <> '001')
select
  magasin.gq_depot,
  magasin.gq_article,
  magasin.gq_physique,
  warehouse.gq_physique as wh_physique
from magasin
left join warehouse on warehouse.gq_article = magasin.gq_article
order by magasin.gq_depot, magasin.gq_article;

如果gq_depot + gq_article在表中是唯一的(例如,构成主键),则上述查询只能正常工作。否则,您需要汇总才能获得每个gq_physique + gq_depot的{​​{1}}。