SQL选择多个值StoredProcedure

时间:2015-12-22 09:32:07

标签: c# sql

我有两张桌子: 设备详细信息:包含每个设备的详细信息 其他表设备记录。

我想在设备列表上创建Select语句,以便从设备详细信息中获取每个设备的最高记录:

SELECT TOP 1
       [t].[DeviceNumber]
     , [d].[CarNumber] AS [CarNumber]
     , [t].TimeStamp
FROM [DeviceRecords] AS [t]
LEFT JOIN [Device_Details] AS [d]
    ON [t].[DeviceNumber] = [d].[AVL_DeviceNumber]
WHERE [t].[DeviceNumber] IN ('013950003919546', '358244017672256', '013950003919876', '013227005026319', '013226001974274') 
ORDER BY
         [t].TimeStamp DESC

我没有在C#中进行For循环,而是单独查询每个设备,而是在考虑如何在一次性查询中执行该操作,返回每个设备的TOP记录。

2 个答案:

答案 0 :(得分:0)

当您可以使用APPLY

时就是这种情况
select t.DeviceNumber, 
       oa.CarNumber, 
       t.TimeStamp
from [DeviceRecords] as t
outer apply(select top 1 CarNumber 
            from [Device_Details] as d 
            where t.DeviceNumber = d.AVL_DeviceNumber 
            order by ... desc) oa   
where t.DeviceNumber in ('013950003919546', '358244017672256',
                         '013950003919876', '013227005026319', '013226001974274')

您应该使用详细信息表中的相应列替换...

答案 1 :(得分:0)

尝试使用子查询

SELECT TOP 1
   [t].[DeviceNumber]
 , [d].[CarNumber] AS [CarNumber]
 , [t].TimeStamp
FROM (Select [i].[DeviceNumber], MAX([i].[TimeStamp]) as 'TimeStamp'
      from [DeviceRecords] AS [i]
      group by [i].[DeviceNumber]) AS [t]
LEFT JOIN AS [d]
    ON [t].[DeviceNumber] = [d].[AVL_DeviceNumber]
WHERE [t].[DeviceNumber] IN ('013950003919546', '358244017672256', '013950003919876', '013227005026319', '013226001974274') 
ORDER BY
         [t].TimeStamp DESC