【问题标题】:T-SQL Select to compute a result row on preceeding group/conditionT-SQL 选择以在前面的组/条件上计算结果行
【发布时间】:2017-09-12 11:00:47
【问题描述】:

如何使用 T-SQL 选择查询来实现此结果。 鉴于此示例表:

    create table sample (a int, b int)

    insert into sample values (999, 10)
    insert into sample values (16, 11)
    insert into sample values (10, 12)
    insert into sample values (25, 13)
    insert into sample values (999, 20)
    insert into sample values (14, 12)
    insert into sample values (90, 45)
    insert into sample values (18, 34)

我正在尝试实现这个输出:

    a           b            result             
    ----------- -----------  ----------- 
    999         10           10 
    16          11           10 
    10          12           10 
    25          13           10 
    999         20           20 
    14          12           20 
    90          45           20 
    18          34           20 

规则相当简单:如果列 'a' 的 special 值为 999,则该行和后续行的结果(除非 'a' 的值再次为 999)将是“b”列的值。假设第一条记录在“a”列上有 999。

如果可能的话,任何提示如何在不使用存储过程或函数的情况下实现选择查询?

谢谢。

安东尼奥

【问题讨论】:

  • SQL Server 没有“后续”行的概念。 SQL 表表示无序集。

标签: sql tsql select


【解决方案1】:

如果你添加一列来指定排序,你可以做你想做的事:

create table sample (
    id int identity(1, 1),
    a int,
    b int
);

然后您可以通过查找最新的“999”版本并复制该值来做您想做的事情。下面是一个使用窗口函数的方法:

select a, b, max(case when a = 999 then b end) over (partition by id_999) as result
from (select s.*,
             max(case when a = 999 then id end) over (order by id) as id_999
      from sample s
     ) s;

【讨论】:

  • 谢谢@GordonLinoff,我看到了你的好主意,它几乎是完美的。但是,使用 max(b) 会导致与预期不同的输出:“结果”列的值是 13 和 45(每个组的最大值,需要的是第一个值 - 值 10 和 20。
  • @AntónioGonçalves 。 . .哎哟。这也需要case,因此“999”中的值就是分配的值。
  • 好的,谢谢。另请查看@Paparazzi 提供的解决方案。
【解决方案2】:

你需要有一个id列

select cn.id, cn.a
     , (select top (1) b from sample where sample.id <= cn.id and a = 999 order by id desc) 
from  sample as cn 
order by id

【讨论】:

  • 非常感谢@Paparazzi
猜你喜欢
  • 1970-01-01
  • 2018-08-15
  • 2012-08-05
  • 1970-01-01
  • 2022-01-26
  • 2019-08-31
  • 1970-01-01
  • 2016-05-01
  • 2013-03-16
相关资源
最近更新 更多