【问题标题】:SQL: Aggregate after join with null checkSQL:加入空值检查后进行聚合
【发布时间】:2011-04-05 17:30:29
【问题描述】:

我有这些表(在 SQL-Server 2008 R2 中):

表1:

Id   Guid
1    {530D8FE1-7541-43CC-9F92-1AA776490155}
2    {CAC5B001-C8DE-46AA-A848-5D831633D0DF}
3    NULL

表2:

Id    Column1    Table2FK
1     1          1
2     1          2
3     1          3

我想执行一个聚合 Table2.Column1 的查询,并将其连接到具有最大 Id 的 Table1 行,但包含 Table1.Guid 的非空值。在这种情况下,它应该加入 Table1 的第 2 行。写成查询我想要这样的东西(虽然这不是有效的 sql):

select t2.Id, t2.Column1, t2.Table2FK, max(t1.Id), t1.Guid 
    from Table2 t2
    join Table1 t1 on t2.Table2FK = t1.Id 
    where t1.Guid is not null
    group by t2.Column1

我已经设法分别对Table2.Id2 进行了空值检查和聚合,但不是在同一个查询中。在第一种情况下,连接返回 2 行,在第二种情况下,它连接到 Table1 的第 3 行。

【问题讨论】:

  • 您尚未指定列在输出结果集中实际期望的内容
  • 我放在select子句中的那些(基本上都是)
  • table2fk 不是 table1 中引用 id 的外键吗?如果是的话,你为什么要在结果中列出它们。我建议多考虑一下这个问题并完善你的问题陈述以获得更好的回应
  • @Aadith Yes table2fk 是 table1 的外键

标签: sql sql-server sql-server-2008


【解决方案1】:

您可以使用外连接来匹配具有非空 guid 的行。然后row_number 可以给每个找到的行一个“排名”,因此最高的 Column1 将具有排名 1:

select  *
from    (
        select  row_number() over (partition by t2.Column1, 
                    order by t2.id desc) as rn
        ,       *
        from    Table2 t2
        left join    
                Table1 t1
        on      t2.Table2FK = t1.id
                and t1.guid is not null
        ) as SubQueryAlias
where   rn = 1

子查询是必需的,因为 SQL Server 不允许在 where 子句中直接使用 row_number

【讨论】:

  • 我认为您在答案中切换了Table1Table2。如果我将它们切换回来,我几乎得到了我想要的结果,但是它返回 2 行,因为它连接了两个表的前 2 行,我希望它返回 Table1 的第二个连接和第二行的连接结果Table2 的最大值(即 Table1 的最大值 Id 其中 Guid is not nullColumn1Table1 分组)。
  • @Rian Schmits:您可以在Column1 上进行分区,而不是在答案中编辑的id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-03
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多