组合SELECT语句。需要帮助

时间:2011-03-16 12:52:35

标签: sql sql-server sql-server-2005 tsql

我有以下两个我真正需要结合的T-SQL语句。

任何帮助都会非常感激。

    SELECT Aircraft.Id AS AircraftID, AircraftManufacturers.Name, AircraftModels.ModelName, 
    Aircraft.ModelSuffix, Aircraft.ImageFileName, Aircraft.Year, Aircraft.SerialNo, 
    Locations.DescriptionForSite, Aircraft.Description, Aircraft.Description2, 
    Aircraft.InfoWebAddress, Aircraft.ImageDescription, Advertisers.Id AS AdvertisersID, 
    Advertisers.Name AS AdvertisersName, Aircraft.AircraftDataId, Aircraft.ForSale, Aircraft.ForLease, 
    Aircraft.TTAF, Aircraft.ReSend, Aircraft.ReSendReason, Aircraft.Registration, Aircraft.AdType,
    Aircraft.HasAlternateImage, Aircraft.AlternateImageDescription, 
    Aircraft.Price, AircraftModels.AircraftType, Advertisers.CurrentEMagLink, Aircraft.CurrentEMagLink, 
    Aircraft.Email, Aircraft.IsSold, Aircraft.SoldDate, Aircraft.DateAdded, Aircraft.ExtendedDetails, 
    Aircraft.LastUpdateDate, Aircraft.ImageCount, Aircraft.ContactTelephone, AircraftModels.id, Advertisers.IsPremiumAdvertiser,
    Aircraft.Location, Advertisers.ContactTelephone As AdvertisersTelephone, Aircraft.LastUpdateDate, Aircraft.EndDate, Aircraft.VideoLink
    FROM (((Aircraft 
    INNER JOIN Advertisers ON Aircraft.AdvertiserId = Advertisers.Id) 
    INNER JOIN AircraftModels ON Aircraft.AircraftModelId = AircraftModels.Id) 
    INNER JOIN AircraftManufacturers ON AircraftModels.ManufacturerId = AircraftManufacturers.Id) 
    INNER JOIN Locations ON Aircraft.LocationId = Locations.Id
    JOIN iter$simple_intlist_to_tbl(@ids) i ON AircraftModels.id = i.number
    WHERE (Aircraft.IsActive=1 AND Advertisers.IsActive=1 AND (Aircraft.EndDate>=@Date OR Aircraft.EndDate Is Null) AND Locations.DescriptionForSite LIKE @Location)
    OR (Advertisers.IsActive=1 AND Aircraft.IsSold=1 AND Aircraft.SoldDate>=@Date2 AND Locations.DescriptionForSite LIKE @Location)
    ORDER BY Advertisers.IsPremiumAdvertiser ASC, Aircraft.DateAdded DESC, Aircraft.ListPosition DESC, 
    Aircraft.LastUpdateDate, AircraftManufacturers.Name, AircraftModels.ModelName, Aircraft.ModelSuffix, 
    Aircraft.Id DESC

    SELECT TOP (1) dbo.Addresses.Email, dbo.Addresses.Contact, dbo.Addresses.Telephone1
    FROM dbo.AdvertiserAddressLink 
    INNER JOIN dbo.Addresses ON dbo.AdvertiserAddressLink.AddressId = dbo.Addresses.Id
    WHERE (dbo.AdvertiserAddressLink.AdvertiserId = 'AdvertisersID') <--see above 
    AND (dbo.Addresses.AddressType = 1 OR dbo.Addresses.AddressType = 0)
    ORDER BY dbo.Addresses.AddressType DESC, dbo.Addresses.Sequence

感谢!!!!

1 个答案:

答案 0 :(得分:2)

您希望在第二个查询中根据第一个查询中的相关参数执行TOP 1吗?

您可以使用APPLY

一个简单的例子。

SELECT t.name, ca.name
FROM sys.tables t
CROSS APPLY (SELECT TOP 1 * 
             FROM sys.columns c 
             WHERE c.object_id=t.object_id 
             ORDER BY name) ca