简体   繁体   English

如何在SQL查询中使用子查询?

[英]How do use a sub-query within a query in SQL?

I'm fairly new to SQL and am having trouble generating the correct information. 我对SQL相当陌生,在生成正确的信息时遇到了麻烦。 I have a data set with FinishedGood part numbers and ProductClassCode, among other things. 我有一个带有FinishedGood零件号和ProductClassCode的数据集。 What I am looking for is all FinishedGood part numbers with multiple ProductClassCode's, one of which is 'WU'. 我要查找的是带有多个ProductClassCode的所有FinishedGood零件号,其中之一是“ WU”。 I can run a query to find all ProductClassCode's equal to WU: 我可以运行查询以查找所有等于WU的ProductClassCode:

select finished_good
from FFTGGM.data_attributes_ext
where prodclass_cd = 'WU'

But I'm having trouble figuring out how to use that query to compare it to all FinishedGood's to generate a list of FinishedGood's with a ProdClasssCode of 'WU' AND something else. 但是我在弄清楚如何使用该查询将其与所有FinishedGood进行比较以生成ProdClasssCode为“ WU”和其他东西的FinishedGood列表时遇到了麻烦。 I know I can use it as a sub-query, but I'm unsure of how to get the correct order for the look up. 我知道我可以将其用作子查询,但是我不确定如何获取正确的查询顺序。 Any advice? 有什么建议吗?

-Edit- -编辑-

Some sample data: 一些样本数据:

样本数据

Or you could do: 或者您可以这样做:

where prodclass_cd in (select distinct prodclass_cd from prodclasstable)

Your criteria in the WHERE clause can then be dynamic. 然后,您在WHERE子句中的条件可以是动态的。

You could use an IN clause or an EXISTS clause: 您可以使用IN子句或EXISTS子句:

select *
from FFTGGM.data_attributes_ext
where finished_good in
(
  select distinct finished_good
  from FFTGGM.data_attributes_ext
  where prodclass_cd = 'WU'
)

or 要么

select *
from FFTGGM.data_attributes_ext A
where 
EXISTS (
  select finished_good
  from FFTGGM.data_attributes_ext B
  where A.finished_good=B.finished_good
    and prodclass_cd = 'WU'
)

If you only want finished goods which have 'WU" and also have another non-WU product-class, you could do two checks, like this: 如果您只想要具有“ WU”且还具有另一个非WU产品类别的制成品,则可以进行两次检查,如下所示:

select *
from FFTGGM.data_attributes_ext A
where 
EXISTS (
  select finished_good
  from FFTGGM.data_attributes_ext B
  where A.finished_good=B.finished_good
    and prodclass_cd = 'WU'
)
and 
EXISTS (
  select finished_good
  from FFTGGM.data_attributes_ext B
  where A.finished_good=B.finished_good
    and prodclass_cd <> 'WU'
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM