Sql 按应用分区后派生列
我有以下资料:Sql 按应用分区后派生列,sql,sql-server,window-functions,derived-column,Sql,Sql Server,Window Functions,Derived Column,我有以下资料: +----+--------+------------------+ | Id | Weight | is_weight_faulty | +----+--------+------------------+ | A | 100 | 1 | | A | 50 | 0 | | A | 10 | 0 | | B | 500 | 0
+----+--------+------------------+
| 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\u weight\u fault
。首先,我将根据Id
应用分区,并根据是否存在重量故障
应用订单。如果对于任何子集,我们在列中发现值1
是错误的weight
我们的正确权重将是weight
=correct\u weight
,其中是错误的=1
,对于该子集的其余条目correct\u weight
将是0
如果我们查看前三行的Id
ACorrect_Weight
将等于第一行的100,而接下来的两行的权重将为0。对于剩余的情况,Correct_Weight
将等于Weight
,因为在应用分区后,我们将获得的每个数据子集都没有is_Weight_fault=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\u Weight\u fault=1
您可以使用max()over()
窗口函数找出每个id
的is\u Weight\u Correct
列的最大值,我无法创建使正确权重
为0的案例。如果为1,则在else
语句的帮助下,将权重
乘以是否正确
架构和插入语句:
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
输出:
身份证件
重量
重量有问题吗
正确重量
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
你试过什么?你在哪里卡住了?你能解释一下你的代码的这一部分吗?
(按id划分)=1
(max(is\u weight\u fault)over(partition by id))正在计算每个id的max(is\u weight\u fault)。如果是1,则表示该特定id至少有一行在is\u weight\u fault列中有1