0

我有三张桌子

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

但我只想记录最近 PatchInstall 日期的每台 PC。我曾尝试使用 GROUP BY 命令执行此操作,但没有任何运气。

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

4

4 回答 4

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
于 2013-03-25T09:33:19.057 回答
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如果不是 1 对 1 的关系,则每一对都会得到一行table2

于 2013-03-25T09:33:01.670 回答
0

尝试:

SELECT
  max(PatchInstall) over (partition by PCName)
FROM YourTable
于 2013-03-25T09:34:22.937 回答
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 小提琴演示

于 2013-03-25T09:49:22.313 回答