SQL:如何从表中获取单个查询信息并从另一个表中获取集合信息?
我在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”。
这应该足够了
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
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
似乎接近我需要的东西。但是我恐怕不会得到与最大SwVersion相关的DeviceType,但是如果我没有弄错的话,最大的DeviceType。 (通常设备类型不会改变,但它是可能的)。 –
能否请你清楚解释一下,这样我就可以从我身边尝试给出更好的解决方案@ groenhen – mohan111
是的,我已经更新了问题中的例子,我想这比我的解释更有意义。这个想法恐怕不是每次都得到DeviceType的最大值(在上面的例子中是3),而不是SwVersion 804的1和SwVersion 806的最大值。 –
尝试:
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;
除此之外,如果你希望在一个表中的记录在没有其他记者使用不同类型的联接。
提示:加入+群组或加入+子查询+群组 – Pred
坦率地说,它就像一个非常基本的查询。你有什么尝试?你做了什么研究?除非我误解,否则你只需要一个'JOIN'和'GROUP BY' ... – Santi