雖然它可能是很有誘惑力使用第二子查詢聯接,以獲得MAX()
,並再次MSISDN
的最大日加入,你應該能夠通過添加MAX(DateRegistered)
到現有的子查詢並添加OR
來實現它條件在聯接的ON
子句中加入MSISDN,mindate
或MSISDN,maxdate
。
SELECT
sa.ContentID,
SA.MSISDN,
-- Use the join's dates by alias in the SELECT
mysa.mindate,
mysa.maxdate
FROM
sms.dbo.SubscriptionsArchive AS sa
INNER JOIN (
SELECT
MSISDN,
MIN(DateRegistered) AS mindate,
-- Add the max date
MAX(DateRegistered) AS maxdate,
FROM sms.dbo.SubscriptionsArchive
GROUP BY MSISDN
) mysa
-- Join on either a mindate or maxdate match
ON (sa.MSISDN = mysa.MSISDN AND sa.DateRegistered = mysa.mindate)
OR (sa.MSISDN = mysa.MSISDN AND sa.DateRegistered = mysa.maxdate)
我注意到你這個標記爲mysql但dbo
真的建議你使用的是MS SQL服務器。如果這是真的,那麼你可以使用公用表表達式而不是子查詢連接。
-- Define the subquery as a CTE instead
WITH mysa AS (
SELECT
MSISDN,
MIN(DateRegistered) AS mindate,
-- Add the max date
MAX(DateRegistered) AS maxdate,
FROM sms.dbo.SubscriptionsArchive
GROUP BY MSISDN
);
SELECT
sa.ContentID,
SA.MSISDN,
-- Use the join's dates by alias in the SELECT
mysa.mindate,
mysa.maxdate
FROM sms.dbo.SubscriptionsArchive AS sa
-- Join on the CTE
INNER JOIN mysa
ON (sa.MSISDN = mysa.MSISDN AND sa.DateRegistered = mysa.mindate)
OR (sa.MSISDN = mysa.MSISDN AND sa.DateRegistered = mysa.maxdate)
你的問題標記爲「MySQL的」,但語法建議的SQL Server。請適當標記問題。 –