SQL - 派生表问题

时间:2011-12-02 09:39:45

标签: sql

我有以下SQL查询:

SELECT VehicleRegistrations.ID, VehicleRegistrations.VehicleReg,  
       VehicleRegistrations.Phone, VehicleType.VehicleTypeDescription, 
       dt.ID AS 'CostID', dt.IVehHire, dt.FixedCostPerYear, dt.VehicleParts, 
       dt.MaintenancePerMile, dt.DateEffective
FROM VehicleRegistrations 
INNER JOIN VehicleType ON VehicleRegistrations.VehicleType = VehicleType.ID 
LEFT OUTER JOIN (SELECT TOP (1) ID, VehicleRegID, DateEffective, IVehHire, 
                    FixedCostPerYear, VehicleParts, MaintenancePerMile
                  FROM  VehicleFixedCosts
                  WHERE (DateEffective <= GETDATE())
                  ORDER BY DateEffective DESC) AS dt 
ON dt.VehicleRegID = VehicleRegistrations.ID

我基本上想要做的是始终从'VehicleFixedCosts'表中选择前1条记录,其中VehicleRegID与主查询中的匹配。这里发生的事情是它在连接之前选择了顶行,所以如果顶行的车辆登记与我们加入的那一行不匹配则返回任何内容。

有什么想法吗?我真的不想为我需要返回的每个列使用子选择

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT vr.ID, vr.VehicleReg,  
       vr.Phone, VehicleType.VehicleTypeDescription, 
       dt.ID AS 'CostID', dt.IVehHire, dt.FixedCostPerYear, dt.VehicleParts, 
       dt.MaintenancePerMile, dt.DateEffective
FROM VehicleRegistrations vr
INNER JOIN VehicleType ON vr.VehicleType = VehicleType.ID 
LEFT OUTER JOIN (
    SELECT ID, VehicleRegID, DateEffective, IVehHire, FixedCostPerYear, VehicleParts, MaintenancePerMile
    FROM VehicleFixedCosts vfc
    JOIN (
        select VehicleRegID, max(DateEffective) as DateEffective
        from VehicleFixedCosts
        where DateEffective <= getdate()
        group by VehicleRegID
    ) t ON vfc.VehicleRegID = t.VehicleRegID and vfc.DateEffective = t.DateEffective
) AS dt 
ON dt.VehicleRegID = vr.ID

dt下面的子查询可能需要一些分组但没有架构(可能是样本数据),很难说哪个列应该参与其中。