在MS Access上,分组然后过滤

时间:2015-11-19 07:30:43

标签: sql ms-access select

我有一个关于ms访问的表,其中包含13列。我想group byName然后通过比较列id检查最新的一个,并在最新一行时记录如果不采取以前的记录有价值。将对每列进行比较。

+-----+-----+-------+-------+-------+
| id  |Name |colum1 |colum2 |colum3 |
+-----+-----+-------+-------+-------+
| 1   |a    |x      |       |x      |
+-----+-----+-------+-------+-------+
| 2   |b    |       |y      |y      |
+-----+-----+-------+-------+-------+
| 3   |a    |z      |z      |       |
+-----+-----+-------+-------+-------+
| 4   |a    |m      |       |       |
+-----+-----+-------+-------+-------+

预期输出

+-----+-----+-------+-------+-------+
| id  |Name |colum1 |colum2 |colum3 |
+-----+-----+-------+-------+-------+
| 2   |b    |       |y      |y      |
+-----+-----+-------+-------+-------+
| 4   |a    |m      |z      |x      |
+-----+-----+-------+-------+-------+

2 个答案:

答案 0 :(得分:0)

你可以做自我加入。

SELECT T1.*
FROM
    table_name T1 
INNER JOIN 
    (SELECT `Name`,MAX(`id`) AS ID FROM table_name GROUP BY `Name` ) T2 
 ON T1.`id`= T2.`ID` AND T1.`Name` = T2.`Name`

希望这有帮助。

答案 1 :(得分:0)

我不确定它是否适用于MS Access。它适用于SQL Server。即使这样,也会很慢。

SELECT
    Groups.Name
    ,(
        SELECT TOP(1) T.colum1
        FROM T
        WHERE T.Name = Groups.Name AND T.colum1 <> ''
        ORDER BY T.ID DESC
    ) AS C1
    ,(
        SELECT TOP(1) T.colum2
        FROM T
        WHERE T.Name = Groups.Name AND T.colum2 <> ''
        ORDER BY T.ID DESC
    ) AS C2
    ,(
        SELECT TOP(1) T.colum3
        FROM T
        WHERE T.Name = Groups.Name AND T.colum3 <> ''
        ORDER BY T.ID DESC
    ) AS C3
FROM
    (
        SELECT Name
        FROM T
        GROUP BY Name
    ) AS Groups