0

我有一个包含日期的表,但我需要知道每个位置条件为真的最新日期,唯一的问题是一旦我添加了一个名为“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

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

已尝试使用子查询,但仍然无法正常工作,下面的子查询

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

有人有其他建议吗?

4

2 回答 2

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 
于 2012-09-20T09:37:42.107 回答
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
于 2012-09-20T09:38:56.753 回答