1

好的,我有两张桌子,像这样:

Person:
| ID | Name |
+----+------+
| 0  | Carl |
+----+------+
| 1  | Max  |
+----+------+
| 2  | Lars |

Status
| PersonID | Submitted  | Status |
+----------+------------+--------+
| 0        | *DATETIME* | 1      |
+----------+------------+--------+
| 0        | *DATETIME* | 1      |
+----------+------------+--------+
| 0        | *DATETIME* | 3      |
+----------+------------+--------+
| 0        | *DATETIME* | 1      |
+----------+------------+--------+
| 1        | *DATETIME* | 5      |
+----------+------------+--------+

我想要得到的是让用户表中的所有人都处于最后提交的状态。

如果我使用这样的东西:

SELECT DISTINCT
    Person.Name As Username,
    Status.Status As Userstatus
FROM Person
LEFT JOIN Status
ON Status.PersonID = Person.ID

我得到这样的结果:

| Username | Userstatus |
+----------+------------+
| Carl     | 1          |
+----------+------------+
| Carl     | 3          |
+----------+------------+
| Max      | 5          |
+----------+------------+
| Lars     | NULL       |
+----------+------------+

那么,我该怎么做呢?在这种情况下,假设最新的 Status.Submitted 为 ==1(Status.PersonID 的最后一行,其中 PersonID == 0),跳过其他 Carls。

编辑:我忘了写我正在使用 SQL Compact。

Edit2:得到了一些很棒的答案,不幸的是我忘了提到我也想获得具有空状态值的用户。我在那里添加了一个新用户到表中

4

5 回答 5

1

试试这个Query

SELECT
    Person.Name As Username,
    Status.Status As Userstatus
FROM Person
INNER JOIN Status
ON Status.PersonID = Person.ID
WHERE Status.Submitted in 
(Select Max(Submitted) from Status group by PersonID)
于 2013-05-21T09:01:08.617 回答
1

我没有精简版,但我认为这应该可行:

SQL-SERVER 2008 示例

select person.name as username,
       x.status as userstatus
from person left join (
      select s.personId, s.status
      from status s join (
        select personId, max(submitted) subs
        from status
        group by personid ) s2
        on s.personid = s2.personid and s.submitted = s2.subs
      ) x on person.id = x.personid

| USERNAME | USERSTATUS |
-------------------------
|     Carl |          1 |
|      Max |          5 |
于 2013-05-21T09:03:05.687 回答
1

将聚合函数max与 group by 语句结合使用。

SELECT
    person.Name As Username,
    s3.status As Userstatus
FROM person
LEFT JOIN (
  select s.person_id, s.status 
  from status s
  join (select max(submitted) as last,person_id
       from status group by person_id) s2
  on s.person_id = s2.person_id
  where s.submitted = s2.last) s3
ON person.id = s3.person_id;

Sql 小提琴: http ://sqlfiddle.com/#!2/9822b/19

于 2013-05-21T08:41:30.503 回答
0

试试这个 -

SELECT Username,Userstatus<br>
FROM
(
    SELECT
    Person.Name As Username,
    Status.Status As Userstatus,
    ROW_NUMBER() OVER (PARTITION BY Status.PersonID ORDER BY Status.Submitted DESC) AS RN,
FROM Person
LEFT JOIN Status
ON Status.PersonID = Person.ID
)
WHERE rn=1
于 2013-05-21T09:23:09.713 回答
0
SELECT
    Person.Name As Username,
    Status.Status As Userstatus
FROM Person
OUTER APPLY (
    SELECT TOP(1)
        *
    FROM Status
    WHERE Status.PersonID = Person.ID
    ORDER BY Status.Submitted DESC
) AS [Status]
于 2013-05-21T08:42:54.310 回答