MAX日期分组不正确

时间:2013-03-28 20:54:08

标签: sql sql-server tsql max

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日期中拉回该字段的值?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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

答案 2 :(得分: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;

您可能需要告诉我们您想要如何处理关系,可能有多个行具有相同的分组和相同的最大值(日期),但是您要添加的列的值不同... < / p>