SQL Group按最新条目

时间:2013-03-25 09:30:10

标签: sql

我有三张桌子

table1      
PCName      PCID
PC1     001
PC2     002
PC3     003

table2
PCID        LastOnline
001     01.02.13
002     05.01.13
003     04.03.13

table3
PCID        PatchInstall
001     03.02.13
001     05.02.13
001     01.02.13
002     06.02.13
002     08.02.13            
003     01.02.13
003     09.02.13
003     10.02.13

I can get the information together like this
PCID    PCName  LastOnline  PatchInstall
001     PC1     01.02.13    03.02.13
001     PC1     01.02.13    05.02.13
001     PC1     01.02.13    01.02.13
002     PC2     05.01.13    06.02.13
002     PC2     05.01.13    08.02.13            
003     PC3     04.03.13    01.02.13
003     PC3     04.03.13    09.02.13
003     PC3     04.03.13    10.02.13

但我希望每台PC上都有最新的PatchInstall日期记录。我已尝试使用GROUP BY命令,但没有任何运气。

有人知道如何使它成为可能吗?

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT 
  t1.pcid,
  t2.name,
  t2.LastOnLine,
  t3.LatestPatchInstall
FROM table1 AS t1
INNER JOIN table2 AS t2 ON t1.pcid = t2.pcid
INNER JOIN
(
  SELECT pcid, MAX(PatchInstall) AS LatestPatchInstall
  FROM table3
  GROUP BY pcid
) AS t3 ON t1.pcid = t3.pcid

答案 1 :(得分:0)

假设table1table2处于一对一关系,这就像使用MAX函数一样简单:

SELECT t1.PCID, PCName, LastOnline, MAX(PatchInstall) AS PatchInstall
FROM table1 t1
INNER JOIN table2 t2 ON t1.PCID = t2.PCID
LEFT OUTER JOIN table3 t3 ON t1.PCID = t3.PCID
GROUP BY t1.PCID, PCName, LastOnline

如果它不是一对一关系,则每个table1 - table2对将获得一行。

答案 2 :(得分:0)

尝试:

SELECT
  max(PatchInstall) over (partition by PCName)
FROM YourTable

答案 3 :(得分:0)

另一种更简单的方法是使用CTEROW_NUMBER()

;WITH CTE AS
(
   SELECT T1.PCName,
          T2.LastOnline,
          T3.PatchInstall,
          ROW_NUMBER() OVER (PARTITION BY T1.PCID ORDER BY T3.PatchInstall DESC) AS RNK
   FROM Table1 T1
   INNER JOIN Table2 T2 ON T2.PCID = T1.PCID
   INNER JOIN Table3 T3 ON T3.PCID = T1.PCID
)


SELECT * FROM CTE
WHERE RNK = 1

SQL FIDDLE DEMO