SQL server create 如何根据前一行条件创建新列
SQL server create how to create a new column based on previous row condition
我正在尝试创建一个新列,其值取决于之前的索引行值,如下例所示:
Index
ID
AGE
SEX
HireMonth
Tag
1
101
23
M
9
101
2
102
32
M
12
102
3
103
25
F
11
1
4
104
29
M
10
104
5
105
45
F
1
1
6
106
21
M
7
106
7
107
56
F
6
107
8
108
12
M
4
108
以下是我创建 Tag
列的方法:
CASE WHEN AGE > 25 AND HireMonth => 9
THEN (next row value = 1 AND same row ID )
ELSE ID
END AS Tag
你试过了吗:
select [Index], ID, AGE, SEX, HireMonth,
CASE WHEN LAG(AGE, 1) OVER (ORDER BY [Index]) > 25 AND LAG(HireMonth, 1) OVER (ORDER BY [Index]) >= 9
THEN 1
ELSE ID
END AS Tag
FROM SOME_TABLE
您可以使用 SELF LEFT JOIN
将每个 ID 与其前一个 ID 相匹配。如果您指出的要求匹配,那么您可以分配 1 否则您分配同一行的 ID,使用 CASE
语句。
SELECT
t1.*,
CASE WHEN t2.ID_ IS NOT NULL THEN 1 ELSE t1.ID_ END AS Tag
FROM tab t1
LEFT JOIN tab t2
ON t1.ID_ = t2.ID_ +1
AND t2.AGE > 25
AND t2.HireMonth > 8
试试看 here.
我正在尝试创建一个新列,其值取决于之前的索引行值,如下例所示:
Index | ID | AGE | SEX | HireMonth | Tag |
---|---|---|---|---|---|
1 | 101 | 23 | M | 9 | 101 |
2 | 102 | 32 | M | 12 | 102 |
3 | 103 | 25 | F | 11 | 1 |
4 | 104 | 29 | M | 10 | 104 |
5 | 105 | 45 | F | 1 | 1 |
6 | 106 | 21 | M | 7 | 106 |
7 | 107 | 56 | F | 6 | 107 |
8 | 108 | 12 | M | 4 | 108 |
以下是我创建 Tag
列的方法:
CASE WHEN AGE > 25 AND HireMonth => 9
THEN (next row value = 1 AND same row ID )
ELSE ID
END AS Tag
你试过了吗:
select [Index], ID, AGE, SEX, HireMonth,
CASE WHEN LAG(AGE, 1) OVER (ORDER BY [Index]) > 25 AND LAG(HireMonth, 1) OVER (ORDER BY [Index]) >= 9
THEN 1
ELSE ID
END AS Tag
FROM SOME_TABLE
您可以使用 SELF LEFT JOIN
将每个 ID 与其前一个 ID 相匹配。如果您指出的要求匹配,那么您可以分配 1 否则您分配同一行的 ID,使用 CASE
语句。
SELECT
t1.*,
CASE WHEN t2.ID_ IS NOT NULL THEN 1 ELSE t1.ID_ END AS Tag
FROM tab t1
LEFT JOIN tab t2
ON t1.ID_ = t2.ID_ +1
AND t2.AGE > 25
AND t2.HireMonth > 8
试试看 here.