如何在SQL中将另一个表加入此代码?

时间:2013-11-05 18:44:22

标签: sql tsql sql-server-2012-express

我需要在下面的代码中加入一个名为IB的表。我需要从IB中提取以下字段:QOO,QOH,QCM和AVG。 JOIN条件是IJ.IJITEM = IB.IBITEM和IJ.IJLOC = IB.IBLOC

;WITH cte AS 
    (
      SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
        rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
      FROM dbo.IJ
    )
    SELECT IJLOC, IJITEM, IJDATE, IJLCGT
    FROM cte WHERE rn = 1;

2 个答案:

答案 0 :(得分:1)

一种方法允许比在最终的SELECT中将IB表连接到“cte”更复杂一点,就是使用当前的一个CTE作为表来嵌套另一个CTE。例如:

;WITH cte AS 
(
    SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
    rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
    FROM dbo.IJ
),
filtered AS (
    SELECT IJLOC, IJITEM, IJDATE, IJLCGT
    FROM cte
    WHERE rn = 1
)
SELECT  ib.QOO, ib.QOH, ib.QCM, ib.[AVG]
FROM    ib
INNER JOIN filtered
        ON filtered.IJITEM = IB.IBITEM
        AND filtered.IJLOC = IB.IBLOC

另一个选项,取决于查询优化器如何处理所有表之间的JOIN,以及如果不需要返回IJ表中的任何字段,是将CTE的结果插入临时表然后加入到那个。例如:

CREATE TABLE #Temp (IJITEM DataType, IJLOC DataType)

;WITH cte AS 
(
    SELECT IJLOC, IJITEM, IJDATE, IJLCGT,
    rn = ROW_NUMBER() OVER (PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC)
    FROM dbo.IJ
)
INSERT INTO #Temp (IJITEM, IJLOC)
    SELECT IJITEM, IJLOC
    FROM cte
    WHERE rn = 1;

SELECT  ib.QOO, ib.QOH, ib.QCM, ib.[AVG]
FROM    ib
INNER JOIN #Temp tmp
        ON tmp.IJITEM = IB.IBITEM
        AND tmp.IJLOC = IB.IBLOC

答案 1 :(得分:0)

;
WITH    cte
          AS ( SELECT   IJLOC ,
                        IJITEM ,
                        IJDATE ,
                        IJLCGT ,
                        rn = ROW_NUMBER() OVER ( PARTITION BY IJITEM, IJLOC ORDER BY IJDATE DESC )
               FROM     dbo.IJ
             )
    SELECT  IJLOC ,
            IJITEM ,
            IJDATE ,
            IJLCGT ,
            IB.QOO ,
            IB.QOH ,
            IB.QCM ,
            IB.[AVG]
    FROM    cte
            INNER JOIN IB ON cte.IJITEM = IB.IBITEM
                             AND cte.IJLOC = IB.IBLOC
    WHERE   cte.rn = 1 ;