我想選擇一組符合特定條件的Ids,並且我努力編寫將返回我想要的SQL查詢。SQL從一個組的兩個表中選擇最大ID
表1:
SelloutPriceID|SiteID|CountryCode|CurrencyCode|RequestID|RequestDateTime|InsertedDateTime
666|1002|BE|EUR|12504|2016-09-02 11:57:12.0000000|2016-11-14 14:27:35.980
667|1002|BE|EUR|12501|2016-09-02 11:57:12.0000000|2016-11-14 14:27:36.600
668|1002|BE|EUR|12507|2016-09-02 11:57:12.0000000|2016-11-14 14:27:36.963
表2:
SelloutPricesAuditID|RequestID|SiteID|CountryCode|InsertedDateTime
1|128|1002|BE|2016-11-14 16:55:29.543
2|12507|1002|BE|2016-11-14 17:07:16.633
我這兩個表試圖按網站ID和COUNTRYCODE則僅獲得該組的最大請求ID。然後加入一起匹配的網站ID和國家代碼和最大請求ID。
如果左錶行不在右表中我希望它被返回。 如果右表的請求ID不等於左表的maxRequestID,我希望該行返回。
這是我到目前爲止有:
SELECT s.*, spa2.*
FROM [SPS_selloutprices].[SelloutPrices] as s WITH (NOLOCK)
inner join (select sp.SiteID, sp.CountryCode, Max(sp.RequestID) as maxrequestid
from SPS_selloutprices.SelloutPrices sp
group by sp.SiteID, sp.CountryCode
) s2
on s2.SiteID = s.SiteID and s.CountryCode = s2.CountryCode and s2.maxrequestid = s.RequestID
full join (select spa.SiteID, spa.CountryCode, MAX(spa.RequestID) as maxrequestid
from sps_pricealerts.SelloutPricesAudit spa
group by spa.SiteID, spa.CountryCode
) spa2
on s.SiteID = spa2.SiteID and s.CountryCode = spa2.CountryCode and s2.maxrequestid = spa2.maxrequestid
完整聯接返回只用右手記錄,然後s2.maxrequestid爲NULL - 這樣行不INNER JOIN回來並消失 - 如果這是一個問題 - 您可能需要檢查 – Cato