【问题标题】:Derive column after Applying Partition by应用分区后的派生列
【发布时间】:2021-07-02 01:58:30
【问题描述】:

我的数据如下:

+----+--------+------------------+
| Id | Weight | is_weight_faulty |
+----+--------+------------------+
| A  |    100 |                1 |
| A  |     50 |                0 |
| A  |     10 |                0 |
| B  |    500 |                0 |
| B  |    200 |                0 |
| B  |     40 |                0 |
| C  |    100 |                0 |
+----+--------+------------------+

我需要创建一个列正确权重,这取决于两个因素Id 和值is_weight_faulty。首先,我将通过Id 应用分区并通过is_weight_faulty 订购。如果对于任何子集,我们在is_weight_faulty 列中找到值1,我们的正确权重将是Weight = Correct_Weight,其中is_weight_faulty = 1 并且对于该子集的剩余条目Correct_Weight 将是0。

如果我们查看Id 的前三行,Correct_Weight 在第一行将等于 100,而对于接下来的两行,它将为 0。对于其余情况,Correct_Weight 将等于 Weight,因为没有记录is_weight_faulty = 1 在应用分区后我们将获得的每个数据子集。

期望的输出

+----+--------+------------------+----------------+
| Id | Weight | is_weight_faulty | Correct_Weight |
+----+--------+------------------+----------------+
| A  |    100 |                1 |            100 |
| A  |     50 |                0 |              0 |
| A  |     10 |                0 |              0 |
| B  |    500 |                0 |            500 |
| B  |    200 |                0 |            200 |
| B  |     40 |                0 |             40 |
| C  |    100 |                0 |            100 |
+----+--------+------------------+----------------+

如果有 is_weight_faulty = 1 的条目,我无法创建将 Correct_Weight 设为 0 的案例

【问题讨论】:

  • 你试过什么?你在哪里卡住了?

标签: sql sql-server window-functions derived-column


【解决方案1】:

您可以使用max()over() 窗口函数找出每个idis_weight_correct 列的最大值。如果是 1,则在 case when else 语句的帮助下将 weightis_weight_correct 相乘。

架构和插入语句:

 create table mytable ( Id varchar(10), Weight int, is_weight_faulty int);
 
 insert into mytable values( 'A'  ,    100 ,                1 );
 insert into mytable values( 'A'  ,     50 ,                0 );
 insert into mytable values( 'A'  ,     10 ,                0 );
 insert into mytable values( 'B'  ,    500 ,                0 );
 insert into mytable values( 'B'  ,    200 ,                0 );
 insert into mytable values( 'B'  ,     40 ,                0 );
 insert into mytable values( 'C'  ,    100 ,                0 );

查询:

 select id, weight, is_weight_faulty, 
 (case when max(is_weight_faulty)over(partition by id)=1 then weight*is_weight_faulty else weight end) correct_weight
 from mytable
 GO

输出:

id weight is_weight_faulty correct_weight
A 100 1 100
A 50 0 0
A 10 0 0
B 500 0 500
B 200 0 200
B 40 0 40
C 100 0 100

dbhere

【讨论】:

  • 你能解释一下你的这部分代码吗(partition by id)=1
  • (max(is_weight_faulty)over(partition by id)) 正在计算每个 ID 的 max(is_weight_faulty)。如果它是 1,则意味着对于该特定 id,至少一行在 is_weight_faulty 列中有 1
猜你喜欢
  • 2016-09-25
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多