我有这个查询,它返回相应字段的最小日期值。
var i=0;
i++;
ons.notification.alert({message: i});
i++;
ons.notification.alert({message: i});
i++;
ons.notification.alert({message: i});
它的输出是
但我想显示同一日期的最大日期值以及最小日期。我如何实现这一目标?
答案 0 :(得分:2)
尽管使用第二个子查询联接来获取MAX()
并再次通过MSISDN
加入最新日期可能很诱人,但您应该可以通过添加{{MAX(DateRegistered)
来实现它。 1}}进入现有子查询并在联接的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 Server。如果是这样,那么您可以使用公用表表达式而不是子查询连接。
-- 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)
答案 1 :(得分:0)
您的语法建议使用SQL Server。如果是这样,我建议使用窗口函数:
SELECT sa.ContentID, SA.MSISDN, sa.DateRegistered AS minDate, sa.DateRegistered AS maxDate
FROM (SELECT sa.*,
MIN(DateRegistered) OVER (PARITION BY sa.MSISDN) as mindr,
MAX(DateRegistered) OVER (PARITION BY sa.MSISDN) as maxdr
FROM sms.dbo.SubscriptionsArchive sa
) sa
WHERE sa.DateRegistered IN (mindr, maxdr);