我有2个不同的查询。是否可以结合这些查询?如果有可能我该怎么办?
查询1:http://pastebin.com/pAdP9Yub
SELECT LatofTruck=Lat, LngofTruck=Lng, SpeedofTruck=Speed
FROM TruckLocation
JOIN Truck AS Trucks ON Trucks.OID=TruckLocation.TruckID
WHERE TruckLocation.OID
IN (
SELECT MAX(TruckLocation_1.OID) AS OID
FROM TruckLocation AS TruckLocation_1
JOIN Truck ON TruckLocation_1.TruckID = Truck.OID GROUP BY
TruckLocation_1.TruckID
)
ORDER BY TruckLocation.ReadTime DESC
查询2:http://pastebin.com/Esx36JHU
SELECT a_TankLevel1,a_TankLevel2,d_AlertStation,StateOutAlarm,StateOutValve,
SensorDataPackage.DeviceID,Branch.FirmName,LatofDealer=Branch.Lat,
LngofDealer=Branch.Lng,Branch.City,Branch.FirmPhone,Branch.DealerAdmin
FROM SensorDataPackage
JOIN Dealer AS Branch ON Branch.DeviceID=SensorDataPackage.DeviceID
WHERE SensorDataPackage.OID
IN (
SELECT MAX (SensorDataPackage.OID)
FROM SensorDataPackage
WHERE SensorDataPackage.readTime > DATEADD(DAY,-100,GETDATE())
GROUP BY SensorDataPackage.DeviceID
)
ORDER BY SensorDataPackage.readTime DESC
答案 0 :(得分:1)
您可以使用UNION ALL
,但必须确保列数和列类型相同。所以:
select a, b, c, from x
union all
select p, q, r, s, t from y
不起作用,但
select a, b, p, q, t from x
union all
select a, b, p, q, t from y
会奏效。
所以在你的情况下,你会得到这样的东西:
-- First query.
SELECT Latitude = Lat
, Longitude = Lng
, SpeedofTruck = Speed
, a_TankLevel1 = null
, a_TankLevel2 = null
, d_AlertStation = null
, StateOutAlarm = null
, StateOutValve = null
, DeviceID = null
, FirmName = null
, City = null
, FirmPhone = null
, DealerAdmin = null
FROM TruckLocation
JOIN Truck AS Trucks ON Trucks.OID=TruckLocation.TruckID
WHERE TruckLocation.OID
IN (
SELECT MAX(TruckLocation_1.OID) AS OID
FROM TruckLocation AS TruckLocation_1
JOIN Truck ON TruckLocation_1.TruckID = Truck.OID GROUP BY
TruckLocation_1.TruckID
)
UNION ALL
-- Second query.
SELECT Latitude = Branch.Lat
, Longitude = Branch.Lng
, SpeedofTruck = null
, a_TankLevel1
, a_TankLevel2
, d_AlertStation
, StateOutAlarm
, StateOutValve
, SensorDataPackage.DeviceID
, Branch.FirmName
, Branch.City
, Branch.FirmPhone
, Branch.DealerAdmin
FROM SensorDataPackage
JOIN Dealer AS Branch ON Branch.DeviceID=SensorDataPackage.DeviceID
WHERE SensorDataPackage.OID
IN (
SELECT MAX (SensorDataPackage.OID)
FROM SensorDataPackage
WHERE SensorDataPackage.readTime > DATEADD(DAY,-100,GETDATE())
GROUP BY SensorDataPackage.DeviceID
)
这将为您提供具有卡车和分支机构的纬度和经度的结果集。
答案 1 :(得分:0)
嗨Common Table Expression会在这种情况下帮助你。如果两个表之间有一些共同因素,则可以将它们放入同一个查询中,并将数据输入到单个查询中。我已多次使用此功能。 View也是一个非常好的替代解决方案。