使用MAX作为日期,但是将列添加到分组上'中断'查询 - 子查询?

时间:2012-09-20 09:31:30

标签: sql sql-server-2008 tsql

我有一个保存日期的表但我需要知道每个位置条件为真的最新日期,只有问题是我添加了一个名为'notes'的列它会破坏查询并返回太多行,当前查询是...

SELECT
        Location,
        MAX(date) AS date,
        type,
        notes
  FROM NotesTable a
 INNER JOIN Location b on a.LocationID = b.LocationID
 INNER JOIN Type c on a.typeid = c.typeid
 WHERE typeid <> 8
 GROUP BY Location, type, notes

如果我注释掉notes列,那么它可以正常工作,但只要我将它添加到分组中,它就会返回比所需更多的行。

尝试过使用子查询,但仍然无法使其工作,

下面的子查询
SELECT
        r.location,
        r.date,
        r.type,
        t.notes
  FROM (SELECT Location, MAX(date), type
          FROM NotesTable a INNER JOIN Location b on a.LocationID = b.LocationID
         INNER JOIN Type c on a.typeid = c.typeid
         WHERE typeid <> 8
         GROUP BY location,type
        ) r
INNER JOIN NotesTable t ON t.date = r.date

有人有任何其他建议吗?

2 个答案:

答案 0 :(得分:2)

select * from
(
     SELECT Location,Date, Type, Notes, Row_Number() Over (Partition By Location, Type order by date desc) RN 
     FROM
          NotesTable a
           INNER JOIN Location b on a.LocationID = b.LocationID
           INNER JOIN Type c on a.typeid = c.typeid
      WHERE typeid <> 8
) v
WHERE rn = 1 

答案 1 :(得分:0)

您的查询几乎正确,您需要在ON子句

中添加此附加条件
    AND
    t.location = r.location AND
    t.type = r.type

完整查询,

SELECT r.location
     , r.DATE
     , r.type
     , t.notes
FROM (
    SELECT Location
         , MAX(DATE) maxDate
         , type
    FROM NotesTable a
        INNER JOIN Location b
            ON a.LocationID = b.LocationID
        INNER JOIN Type c
            ON a.typeid = c.typeid
    WHERE typeid <> 8
    GROUP BY location
            , type
    ) r
INNER JOIN NotesTable t
    ON t.DATE = r.maxDate AND
        t.location = r.location AND
        t.type = r.type