SQL:如何从表中获取单个查询信息并从另一个表中获取聚合信息?

时间:2017-07-19 13:08:10

标签: sql sql-server

我在Windows7上使用MS SQL Server 2014 我有一个名为" PollingStatus "。的表 以下查询:

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   

ie:与我现有的查询相比,我想从第二个表" DeviceProperties中获得DeviceType和设备的最大 SwVersion &#34 ;.

3 个答案:

答案 0 :(得分:1)

这应该足够了

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/dashboard', 'DashboardController@index');
Route::resource('/bookings', 'BookingsController');
Route::get('/dashboard2', function () {
    return view('dashboard2');
});

答案 1 :(得分: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 

答案 2 :(得分: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;

除此之外,如果您希望一个表中的记录在另一个表中没有对应,则使用不同类型的连接。