2017-07-19 133 views
0

我在Windows7上使用MS SQL Server 2014。
我有一個名爲「PollingStatus」的表。
下面的查詢:SQL:如何從表中獲取單個查詢信息並從另一個表中獲取集合信息?

SELECT DeviceIP 
     ,ServiceStatus 
     ,ReportedErrors 
FROM PollingStatus 

...給出了這樣一些信息:

DeviceIP | ServiceStatus | ReportedErrors 
10.20.1.1 |   0   |   0  
10.20.1.2 |   0   |   0  

而在另一臺命名爲 「DeviceProperties」 我有這樣的:

DeviceIP | DeviceType  | SwVersion 
10.20.1.1 |   3   |  800  
10.20.1.1 |   2   |  802  
10.20.1.1 |   1   |  804  
10.20.1.2 |   2   |  800  
10.20.1.2 |   3   |  801  
10.20.1.2 |   2   |  806  

我需要的是一個查詢來得到像這樣的東西:

DeviceIP | ServiceStatus | ReportedErrors | DeviceType | SwVersion 
10.20.1.1 |  0  |  0   | 1  | 804 
10.20.1.2 |  0  |  0   | 2  | 806 

即:與我現有的查詢相比,我想也有設備類型和設備的最大SwVersion,從第二個表「DeviceProperties」。

+1

提示:加入+羣組或加入+子查詢+羣組 – Pred

+0

坦率地說,它就像一個非常基本的查詢。你有什麼嘗試?你做了什麼研究?除非我誤解,否則你只需要一個'JOIN'和'GROUP BY' ... – Santi

回答

1

這應該足夠了

SELECT DeviceIP 
    ,ServiceStatus 
    ,ReportedErrors 
    ,Max(SwVersion) as MaxSwVersion 
FROM PollingStatus p 
     INNER JOIN DeviceProperties d 
      ON p.DeviceIP = d.DeviceIP 
GROUP BY DeviceIP, ServiceStatus, ReportedErrors 
1
Select 
D.DeviceIP, 
D.ReportedErrors, 
D.ServiceStatus, 
DD.DeviceType, 
DD.SwVersion 
from @Device D 
INNER JOIN (Select 
       DeviceIP, 
       MIN(DeviceType)DeviceType, 
       MAX(SwVersion)SwVersion 
         from @Devicetype 
GROUP BY DeviceIP)DD 
ON D.DeviceIP = DD.DeviceIP 
+0

似乎接近我需要的東西。但是我恐怕不會得到與最大SwVersion相關的DeviceType,但是如果我沒有弄錯的話,最大的DeviceType。 (通常設備類型不會改變,但它是可能的)。 –

+0

能否請你清楚解釋一下,這樣我就可以從我身邊嘗試給出更好的解決方案@ groenhen – mohan111

+0

是的,我已經更新了問題中的例子,我想這比我的解釋更有意義。這個想法恐怕不是每次都得到DeviceType的最大值(在上面的例子中是3),而不是SwVersion 804的1和SwVersion 806的最大值。 –

1

嘗試:

SELECT 
     ps.DeviceIp, 
     ps.ServiceStatus, 
     ps.ReportedErrors, 
     dp.DeviceType, 
     Max(dp.SwVersion) 
    FROM PollingStatus ps 
    INNER JOIN DeviceProperties dp ON dp.DeviceIp = ps.DeviceIp 
    GROUP BY ps.DeviceIp, ps.ServiceStatus, ps.ReportedErrors, dp.DeviceType; 

除此之外,如果你希望在一個表中的記錄在沒有其他記者使用不同類型的聯接。