sql - 从同一个名称获取不同ID的结果

时间:2017-10-05 15:06:46

标签: sql sql-server

我想从sql查询中获得一些帮助:

我有这两张桌子:

表1:

文档:

id<- unqiue key  |  docName  | userName
-----------------|-----------|-----------
 1               | document  | Me
 2               | testDoc   | Friend1
 3               | document  | Me`

和表2:

历史:

docId <-Unique Key | status | time of modification
-------------------|--------|---------------------
 1                 | Good   |  2008-08-08
 2                 | Bad    |  2012-05-17
 3                 | OK     |  2017-10-01

如何查询所有docName s(表docs中的相同docName和userName),我们获取最新统计信息?

这是我要找的结果:

 docName | userName | status
---------|----------|-------- 
 document|  Me      | OK
 testDoc |  Friend1 | Bad

也许:

SELECT docs.docName, MAX(history.status), MAX(userName) 
from docs JOIN
     history
     ON docs.id = history.docId
GROUP by docs.docName;

2 个答案:

答案 0 :(得分:1)

一种方法是相关子查询。在ANSI标准SQL中,这将是:

select d.*,
       (select h.status
        from history h
        where h.docid = d.id
        order by h.modification_time desc
        fetch first 1 row only
       ) as most_recent_status
from docs d;

在SQL Server中,通常使用top 1而不是fetch子句。在MySQL中,你拼写&#34;只获取前1行&#34; as&#34;限制1&#34;。

答案 1 :(得分:1)

如果你想按照你的样本输出,你可以使用CTE,即:

;WITH cte AS (
  SELECT docName, 
         userName, 
         ROW_NUMBER() OVER 
              (PARTITION BY docName, userName 
               ORDER BY [time of modification] DESC) rn, 
         [status]
  FROM docs d
  JOIN history h on h.docId = d.id
  )
SELECT docName, userName, [status] 
FROM cte
WHERE rn = 1

结果:

docName    userName   status
---------- ---------- ----------
document   Me         OK
testDoc    Friend1    Bad