1
SELECT
    ij.IJITEM AS Part,
    ij.IJLOC AS Location,
    ib.IFQOH AS QOH,
    MAX(ij.IJDATE) AS Inv_Date
FROM
    dbo.S2K_IJALL ij
    LEFT OUTER JOIN dbo.S2K_IB ib 
    ON ib.IFITEM = ij.IJITEM AND ib.IFLOC = ij.IJLOC
WHERE
    IJITEM LIKE '%-IC'
AND
    IJRBAL < 0
GROUP BY
    ij.IJITEM,
    ij.IJLOC,
    ib.IFQOH

我需要在上面的查询中添加一个字段。当我这样做时,MAX 日期字段不会保持。我得到添加的字段具有值的每条记录。我怎样才能拉回 MAX 日期该字段的值?

4

3 回答 3

0

假设 SQL Server 2005 或更高版本(请始终指定您的版本!):

;WITH x AS 
(
  SELECT
    ij.IJITEM AS Part,
    ij.IJLOC AS Location,
    ib.IFQOH AS QOH,

    -- any other non-grouping column(s) can go here,

    ij.IJDATE AS Inv_date,
    rn = ROW_NUMBER() OVER (PARTITION BY
      ij.IJITEM, ij.IJLOC, ib.IFQOH ORDER BY ij.IJDATE DESC)
  FROM
    dbo.S2K_IJALL ij
    LEFT OUTER JOIN dbo.S2K_IB ib 
    ON ib.IFITEM = ij.IJITEM AND ib.IFLOC = ij.IJLOC
  WHERE IJITEM LIKE '%-IC'
  AND IJRBAL < 0
)
SELECT Part, Location, QOH, Inv_date
  FROM x WHERE rn = 1;

您可能需要告诉我们您想如何处理平局,可能有多行具有相同的分组和相同的 max(date) 但您要添加的列的值不同...

于 2013-03-28T21:08:34.353 回答
0

将上面的查询加入到包含关键字段上的新字段以及 IJDate = Inv_Date 的表中,这实际上是 MAX(IJDATE)。选择第一个查询中的所有字段以及新字段。

于 2013-03-28T20:58:09.197 回答
0

如果您有更多列要添加,并且结果在您 时变得混乱GROUP BY,您可以更改查询以使用子查询:

select ij.IJITEM AS Part,
  ij.IJLOC AS Location,
  ib.IFQOH AS QOH,
  ij2.ijdate Inv_date,
  --- add other columns
from dbo.S2K_IJALL ij1
inner join
(
  select MAX(IJDATE) ijdate, IJITEM, IJLOC
  from dbo.S2K_IJALL
  WHERE IJITEM LIKE '%-IC'
    AND IJRBAL < 0
  group by IJITEM, IJLOC
) ij2
  on ij1.ijdate = ij2.ijdate
  and ij1.IJITEM = ij2.IJITEM
  and ij1.IJLOC = ij2.IJLOC
LEFT OUTER JOIN dbo.S2K_IB ib 
  ON ib.IFITEM = ij1.IJITEM 
  AND ib.IFLOC = ij1.IJLOC
WHERE ij1.IJITEM LIKE '%-IC'
  AND ij1.IJRBAL < 0
于 2013-03-28T20:59:42.173 回答