虽然它可能是很有诱惑力使用第二子查询联接,以获得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。请适当标记问题。 –