如果我有相同的信息,请选择一条特定的行

时间:2016-11-12 18:37:28

标签: sql-server sql-server-2008 sql-server-2008-r2

我有一个数据表如下:

+--------+----------+-------+------------+--------------+
| month  |   code   |  type   |      date       |    PersonID  |
+--------+----------+-------+------------+--------------+
| 201501 |   178954 |     3 | 2014-12-3  |           10 |
| 201501 |   178954 |     3 | 2014-12-3  |           10 |
| 201501 |   178955 |     2 | 2014-12-13 |           10 |
| 201501 |   178955 |     2 | 2014-12-13 |           10 |
| 201501 |   178956 |     2 | 2014-12-11 |           10 |
| 201501 |   178958 |     1 | 2014-12-10 |           10 |
| 201501 |   178959 |     2 | 2014-12-12 |           15 |
| 201501 |   178959 |     2 | 2014-12-12 |           15 |
| 201501 |   178954 |     1 | 2014-12-11 |           13 |
| 201501 |   178954 |     1 | 2014-12-11 |           13 |
+--------+----------+-------+------------+--------------+

在我的前6行中,我在同一个月中相同的PersonID 如果我在相同的personID ,我想要的是什么>同一个月我想选择类型为2 最近日期的人,在我的情况下,输出将如下所示:< / p>

+--------+--------+------+------------+----------+
| month   |  code    | type|    date       | PersonID |
+--------+--------+------+------------+----------+
| 201501 | 178955 |    2 | 2014-12-13 |       10 |
| 201501 | 178959 |    2 | 2014-12-12 |       15 |
| 201501 | 178954 |    2 | 2014-12-11 |       13 |
+--------+--------+------+------------+----------+

如果它们是一些重复的行,我不想显示它

他们可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

只需使用GROUP BY: https://msdn.microsoft.com/de-de/library/ms177673(v=sql.120).aspx

SELECT mont, code, ... FROM tabelname GROUP BY PersonID, date, ...

请注意,您必须指定组中的所有列。

答案 1 :(得分:0)

SELECT DISTINCT A.month, A.code, A.type, B.date, B.PersonID FROM YourTable A
INNER JOIN (SELECT PersonID, MAX(date) as date FROM YourTable
GROUP BY PersonID) B
ON (A.PersonID = B.PersonID
AND A.date = B.date)
WHERE A.type = 2 ORDER BY B.date DESC, A.PersonID

以防万一您/其他人仍在想。