我有如下查询:
SELECT
IsTestBatch,
BatchID,
CampaignID,
IF(ActualTriggerDateTime IS NOT NULL,
MIN(ActualTriggerDateTime),
MIN(TriggerDateTime)) AS NextQueuedOn
FROM
campaignbatches
WHERE
Status IN (2,3)
GROUP BY
CampaignID
ORDER BY
IF(ActualTriggerDateTime IS NOT NULL, ActualTriggerDateTime, TriggerDateTime) ASC
if
条件无法正常运行,并且MIN日期不符合我的预期。
我期望上面的记录,但是它从表中返回上一张图像的第一条记录:
答案 0 :(得分:4)
由于聚合函数MIN()
忽略了NULL
的值,因此您可以尝试从 ActualTriggerDateTime 列中选择最小日期,在特殊情况下,所有值均为NULL在此列上,然后从 TriggerDateTime 列中选择最小值。
SELECT
IsTestBatch,
BatchID,
CampaignID,
IFNULL(MIN(ActualTriggerDateTime), MIN(TriggerDateTime)) AS NextQueuedOn
FROM
campaignbatches
WHERE
Status IN (2,3)
GROUP BY
IsTestBatch, BatchID, CampaignID
ORDER BY
NextQueuedOn ASC
答案 1 :(得分:0)
所有选择列都将按子句分组
SELECT IsTestBatch,BatchID,CampaignID,
coalesce(MIN(ActualTriggerDateTime),MIN(TriggerDateTime)) AS NextQueuedOn
FROM campaignbatches
WHERE Status IN (2,3)
and IsTestBatch=1 and BatchID=42 -- as you want single row
GROUP BY IsTestBatch,BatchID,
CampaignID
ORDER BY NextQueuedOn ASC