[英]SQL to select a new column based on certain conditions
create table so (
id int
,column1 int
,column2 varchar(1)
);
insert into so values
(1, 1, 'Y')
,(2, 1, 'Y')
,(3, 1, 'N')
,(4, 1, 'N')
,(5, 1, 'Y')
,(6, 1, 'Y')
,(7, 1, 'Y')
,(8, 1, 'Y')
,(9, 2, 'Y')
,(10, 2, 'Y')
,(11, 2, 'N');
with str as (
select
*
,min(id) over (partition by column1) id_start
,case column2
when 'N'
then row_number() over (
partition by column1
order by column2, id
)
else null
end n_value
from
so
), cls as (
select
*
,case
when id_start = id
then 1
else
coalesce(max(n_value) over (
partition by column1
order by id
rows between unbounded preceding and current row
) + 1 ,1)
end column3
from
str
)
select
id
,column1
,column2
,column3
from
cls
order by
id
如其他評論和答案所示,您需要一個訂購密鑰才能使此操作成功。 我在 DDL 中人為地創建了一個,盡管您當然可以使用row_number()
和不同的排序鍵自己構建另一個。
答案中的str
CTE 提供了兩個非常關鍵的列,它們從排序中提取隱式數據: id_start
和n_value
。
id_start
:提供排序鍵值id
,其中每個column1
發生變化。 在您對column3
的定義中,這基本上是您的第三個項目符號。
n_value
:我們需要知道column3
的值變化的次數。 根據您的定義,這僅在column2 = 'N'
時發生,因此該列返回在column1
分區中發生這種情況的次數。
一旦我們有了這兩個數據,避免這個問題的迭代就很簡單了: column3
是所有先前n_value
的最大值加一。 一個例外是當 Y 緊跟在分區的開頭時,在這種情況下column3
始終為 1。(這是通過合並解決的。)
這是一個使用 PostgreSQL 的SqlFiddle 。 Netezza 是一個變體,所以語法在那里仍然有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.