[英]Create new column based on values of another column
I'm new to SQL, I use R most of the times. 我是SQL的新手,大多数时候我都使用R。 However the requirement is I fulfil this in SQL
但是要求是我在SQL中实现
I have a table in MS SQL where each row is one 'Activity Type' which has a value of either 'A','B' or 'C'. 我在MS SQL中有一张表,其中每一行都是一个“活动类型”,其值为“ A”,“ B”或“ C”。 I have a total of 40 columns and I need to check every row if the data is correct.
我总共有40列,我需要检查每一行数据是否正确。 A small example below has few columns.
下面的一个小示例很少有专栏。
The rule is that if the Activity Type is 'A' then all the columns that are MonitorA_
should have a value, everything else should be NULL. 规则是,如果“活动类型”为“ A”,则所有
MonitorA_
列都应有一个值,其他所有内容都应为NULL。 If Activity type is 'B' then all the MonitorB_ columns should have a value, rest all should be NULL 如果活动类型为“ B”,则所有MonitorB_列均应有一个值,其余所有均应为NULL
In the example below, row 1 and row 2 are fine. 在下面的示例中,第1行和第2行很好。 But row 3 and row 4 have problems.
但是第3行和第4行有问题。 That is in row 3, Activity type is 'B' but there is a value in the column 'MonitorC_ID'.
即在第3行中,活动类型为“ B”,但“ MonitorC_ID”列中有一个值。
I want to be able to create a new column with a value of True or False, depending on whether it passed the test. 我希望能够根据其是否通过测试来创建一个值为True或False的新列。
| Activity Type | MonitorA_ID | MonitorA_Date | MonitorA_Region | MonitorB_ID | MonitorB_Date | MonitorB_Region | MonitorC_ID | MonitorC_Date | MonitorC_Region |
|---------------|-------------|---------------|-----------------|-------------|---------------|-----------------|-------------|---------------|-----------------|
| B | NULL | NULL | NULL | 1 | 21/10/1985 | Brisbane | NULL | NULL | NULL |
| A | 45 | 25/03/1986 | Gold Coast | NULL | NULL | NULL | NULL | NULL | NULL |
| B | NULL | NULL | NULL | 67 | 13/03/1959 | Dubai | 45 | NULL | NULL |
| C | NULL | 13/08/1964 | NULL | NULL | NULL | NULL | 82 | 13/08/1964 | Dubai |
You can create a check variable for each type of column A, B, or C. This would give you 3 new fields A_Chk, B_Chk, and C_Chk. 您可以为A,B或C列的每种类型创建一个检查变量。这将为您提供3个新字段A_Chk,B_Chk和C_Chk。 If they are 0, the row is fine but if they are a 1 then the row is bad.
如果它们是0,则行是好的,但是如果它们是1,则行是坏的。
To get to one field, you would just check for the SUM of the 3 chk fields to be zero. 要进入一个字段,您只需检查3个chk字段的总和为零即可。
Select
CASE
WHEN [Activity Type] = 'A' THEN
CASE WHEN MonitorA_ID is NULL
OR MonitorA_Date is NULL
OR MonitorA_Region is NULL
THEN 1 ELSE 0 END
END as 'A_Chk'
From Table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.