我需要查询帮助。我想按ID字段和日期字段的MIN()对查询进行分组。但是,我想要将来所有日期的最小值。
我需要子查询吗?以下内容将排除将来不会发生的所有记录。
SELECT CompanyCode, MIN(NextDate) AS NextFollowUpDate
FROM dbo.LeadNote AS LeadNote
GROUP BY CompanyCode
HAVING (MIN(NextDate) > GETDATE())
答案 0 :(得分:2)
只需使用常规位置:
SELECT CompanyCode, MIN(NextDate) AS NextFollowUpDate
FROM dbo.LeadNote AS LeadNote
WHERE NextDate > GETDATE()
GROUP BY CompanyCode
如果您需要每个公司代码都包含缺失项目的空值,您可以执行此操作
SELECT cc.CompanyCode, g.NextFollowUpDate
FROM
(
SELECT DISTINCT CompanyCode
FROM dbo.LeadNote
) AS cc
LEFT JOIN
(
SELECT CompanyCode, MIN(NextDate) AS NextFollowUpDate
FROM dbo.LeadNote
WHERE NextDate > GETDATE()
GROUP BY CompanyCode
) AS g ON cc.CompanyCode = g.CompanyCode