【问题标题】:T-SQL: number of attribute changes by groupT-SQL:按组的属性更改次数
【发布时间】:2018-06-07 15:08:50
【问题描述】:

我正在寻找一种方法来计算特定组(例如客户)的属性更改次数。

数据

Customer  |  Attribute
A         |  x
A         |  x
A         |  y
A         |  x
A         |  y
B         |  x
B         |  y
B         |  x
C         |  x

结果

Customer  |  Attribute
A         |  3
B         |  2
C         |  0

我尝试过使用 DISTINCT,但是这并没有捕捉到客户 A 的情况,客户 A 的值变回其初始值。

感谢和问候

【问题讨论】:

  • 更改次数?根据什么?
  • SQL 表代表 无序 集。我们需要一列来指定排序。

标签: sql sql-server tsql count


【解决方案1】:

表格代表无序集合。所以,让我假设您有另一列指定排序,我将用? 表示。

那么你可以使用lag()(或lead()):

select customer,
       sum(case when prev_attribute <> attribute then 1 else 0 end) as num_changes
from (select t.*, lag(attribute) over (partition by customer order by ?) as prev_attribute
      from t
     ) t
group by customer;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多