SQL中from子句中的Sub Query

时间:2013-12-16 22:05:19

标签: sql subquery

我有两个问题,我相信我需要在查询号码FROM语句中输入第二个查询,您能告诉我最好的方法吗?

QUERY1

SELECT   PARTNO_AUD, PARTNO_ING, COSTSET_AUD, 
        ITEMVER_AUD, PROCNO_AUD, PROCVER_AUD, PROCSTAGE_AUD, 
        ALLITEM_AUD, COSTERR, 
        dbo.SSI_DAVL_FUNC('COSTERR', COSTERR, 'E') AS DESCRIPTION
  FROM  dbo.MBI030
 WHERE  (PARTNO_ING <> N'') 
   AND (PROCNO_AUD <> N'') 
   AND (COSTERR <> N'00')

QUERY2

SELECT  PARTNO_B02PAR, PARTNO_B02COM, 
        QTYOFF / (100 - PSLOSS) * 100 AS QTY
  FROM  dbo.MBB020

PARTNO_AUDPARTNO_B02PAR相同,PARTNO_INGPARTNO_B02COM相同

3 个答案:

答案 0 :(得分:3)

我假设您要做的就是同时加入表格以查看输出

SELECT 
    PARTNO_AUD, 
    PARTNO_ING, 
    COSTSET_AUD, 
    ITEMVER_AUD, 
    PROCNO_AUD, 
    PROCVER_AUD, 
    PROCSTAGE_AUD,
    ALLITEM_AUD, 
    COSTERR, 
    dbo.SSI_DAVL_FUNC('COSTERR', COSTERR, 'E') AS DESCRIPTION,
    QTY 
FROM dbo.MBI030 A
    INNER JOIN (
        SELECT 
            PARTNO_B02PAR, 
            PARTNO_B02COM, 
            QTYOFF / (100 - PSLOSS) * 100 AS QTY 
        FROM dbo.MBB020) B
    ON A.PARTNO_AUD =B.PARTNO_B02PAR 
         AND A.PARTNO_ING =B.PARTNO_B02COM
WHERE (PARTNO_ING <> N'') 
    AND (PROCNO_AUD <> N'') 
    AND (COSTERR <> N'00')

有关联接的详细信息,请参阅This Link about Joins

答案 1 :(得分:1)

类似的东西:

SELECT   PARTNO_AUD, PARTNO_ING, COSTSET_AUD, 
        ITEMVER_AUD, PROCNO_AUD, PROCVER_AUD, PROCSTAGE_AUD, 
        ALLITEM_AUD, COSTERR, 
        dbo.SSI_DAVL_FUNC('COSTERR', COSTERR, 'E') AS DESCRIPTION
  FROM  dbo.MBI030
  inner join dbo.MBB020 on PARTNO_AUD = PARTNO_B02PAR and PARTNO_ING = PARTNO_B02COM
 WHERE  (PARTNO_ING <> N'') 
   AND (PROCNO_AUD <> N'') 
   AND (COSTERR <> N'00')

但您可能想要更改所选内容,可以添加:

PARTNO_B02PAR, PARTNO_B02COM, 
        QTYOFF / (100 - PSLOSS) * 100 AS QTY

如果你愿意的话。

答案 2 :(得分:1)

看起来你想要加入。尝试

SELECT  q1.PARTNO_AUD, q1.PARTNO_ING, q1.COSTSET_AUD, 
        q1.ITEMVER_AUD, q1.PROCNO_AUD, q1.PROCVER_AUD, q1.PROCSTAGE_AUD, 
        q1.ALLITEM_AUD, q1.COSTERR, 
        dbo.SSI_DAVL_FUNC('COSTERR', q1.COSTERR, 'E') AS DESCRIPTION, q2.qty
FROM  dbo.MBI030 q1
   INNER JOIN 
   (
       SELECT  PARTNO_B02PAR, PARTNO_B02COM, QTYOFF / (100 - PSLOSS) * 100 AS QTY
       FROM  dbo.MBB020
   ) q2 ON q1.PartNO_AUD = q2.PARTNO_B02PAR AND q1.PARTNO_ING = q2.PARTNO_B02COM
WHERE  (q1.PARTNO_ING <> N'') 
    AND (q1.PROCNO_AUD <> N'') 
    AND (q1.COSTERR <> N'00')

诀窍是将查询放在括号中并给它一个别名,例如q2。

适用于连接和来自。