一对多连接中的限制记录

时间:2019-04-06 02:56:19

标签: sql sql-server

我正在尝试生成记录列表,其中标头包含单个记录,并且日志中的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

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您似乎想要:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! YourCell
    cell.yourTextField.becomeFirstResponder()
}

答案 2 :(得分:0)

从查询中我了解到的是,有一个表名表我有一个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'