繁体   English   中英

一对多连接中的限制记录

[英]Limiting records in a one-to-many join

我正在尝试生成记录列表,其中标头包含单个记录,并且日志中的FIRST条目表示记录的创建日期。 所有其他详细记录都是不必要的,并且在我只需要第一个时会创建多个结果。

我已经尝试过“分组依据”,自我加入,独立等,但是到目前为止,我所做的一切都没有达到预期的效果。 我觉得我在这里确实缺少一些明显的东西。

这就是我正在使用的:

SELECT i.id
    ,l.CreateDate
    ,i.departmentname
    ,i.productkey
    ,c.Description
FROM dbo.table i (NOLOCK)

JOIN dbo.log l ON i.id = l.id

JOIN dbo.LU_Table c ON i.id = c.ID

WHERE l.CreateDate > '2019-04-01'

AND l.CreateDate < '2019-04-30'

我想看看:

ID# 1, 04/05/2019, Department, Product, Description
ID# 2, 04/05/2019, Department, Product, Description
ID# 3, 04/05/2019, Department, Product, Description
ID# 4, 04/05/2019, Department, Product, Description

相反,我得到:

ID# 1, 04/05/2019, Department, Product, Description
ID# 1, 04/06/2019, Department, Product, Description
ID# 1, 04/07/2019, Department, Product, Description
ID# 1, 04/08/2019, Department, Product, Description
ID# 1, 04/09/2019, Department, Product, Description
ID# 2, 04/05/2019, Department, Product, Description
ID# 2, 04/06/2019, Department, Product, Description
ID# 2, 04/07/2019, Department, Product, Description
ID# 2, 04/08/2019, Department, Product, Description
ID# 2, 04/09/2019, Department, Product, Description

我认为最简单的方法是将Order By放在where子句之后。 因此它看起来像是ORDER BY l.CreateDate, i.id ASC ,应该可以解决问题。

您似乎想要:

SELECT i.id, l.CreateDate, i.departmentname, i.productkey, c.Description
FROM dbo.table i JOIN
     (SELECT l.id, MIN(l.CreateDate) as CreateDate
      FROM dbo.log l
      GROUP BY l.id
     ) l
     ON i.id = l.id JOIN
     dbo.LU_Table c
     ON i.id = c.ID
WHERE l.CreateDate > '2019-04-01' AND
      l.CreateDate < '2019-04-30';

我从查询中了解到的是,有一个表名表我有一个ID记录,而日志表可能有多个记录针对每个ID。

您可以通过为日志表创建派生表来实现。

衍生表

Select  row_number() over(partition by ID order by ID) srno     
          , ID 
          , creation_date
   From log

尝试这个

SELECT i.id
    ,l.CreateDate
    ,i.departmentname
    ,i.productkey
    ,c.Description
FROM dbo.table i (NOLOCK)
JOIN (Select  row_number() over(partition by ID order by ID) srno       
              , ID 
              , creation_date
       From log ) l  on l.id = i.id and  l.srno = 1

JOIN dbo.LU_Table c ON i.id = c.ID
WHERE l.CreateDate > '2019-04-01'

AND l.CreateDate < '2019-04-30'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM