Select 每个联系人的最早日期

Select earliest date for each Contact

我有以下查询,它应该只提取每个联系人的最早日期,但它提取了所有可用日期。我在这里查看了多个线程,但无法解决。 这是使用 SQL Server 2005。

SELECT DISTINCT o.SubscriberKey, MIN(o.EventDate) as OpenDate
FROM _Open o 
INNER JOIN _Job j
    ON o.JobID = j.JobID
GROUP BY o.SubscriberKey, o.EventDate

目前,我得到这样的结果:

Subscriber 1  17 July 2019 06:04
Subscriber 1  17 July 2019 06:05
Subscriber 1  18 July 2019 04:29
Subscriber 2  18 July 2019 07:04
Subscriber 2  18 July 2019 07:21
Subscriber 2  24 July 2019 05:40

以及我想达到的目标:

Subscriber 1  17 July 2019 06:04
Subscriber 2  18 July 2019 07:04
SELECT 
     --you dont want to have a DISTINCT here, you are doing a GROUP BY so its not needed 
    --DISTINCT
    o.SubscriberKey
    , MIN(o.EventDate) as OpenDate
FROM _Open o 
    --Join is not referenced. Thanks @Gordon Linoff
    --INNER JOIN _Job j
    --    ON o.JobID = j.JobID
GROUP BY
    o.SubscriberKey
    --dont group on Event date, this is stopping the MIN function from aggregating the rows.
    --, o.EventDate

您不需要 JOIN。你需要修复 GROUP BY:

SELECT o.SubscriberKey, MIN(o.EventDate) as OpenDate
FROM _Open o 
GROUP BY o.SubscriberKey;

你只需要 JOIN 如果它是过滤结果,但我怀疑是这种情况。

您只需要 group by SubscriberKey 并在 EventDate 上聚合。
你也加入了 _Job 但你没有使用它。
除非您只想获得表的匹配行的最小值 EventDate,否则不需要此连接:

SELECT SubscriberKey, MIN(EventDate) as OpenDate
FROM _Open 
GROUP BY SubscriberKey