簡體   English   中英

select 語句中的更新語句

[英]Update statement within select statement

我正在嘗試編寫一個查詢,在該查詢中我根據其他條件更新計數器。 例如:

with table 1 as (select *, count from table1)

select box_type, 
case when box_type = lag(box_type) over (order by time) 
then 
  count, update table1 set count = count + 1
else
  count
end as identifier

這是我正在嘗試做的基本要點。 我想要一個看起來像這樣的表:

box_type 標識符
小的 1
小的 1
小的 1
中等的 2
中等的 2
大的 3
大的 3
小的 4

我只想在 box_type 每次更改時增加該標識符值

謝謝!

只有當您有一個指定排序的列時,您的問題才有意義。 讓我假設存在這樣一個列 - 根據您的代碼,我將其稱為time

然后,您可以使用lag()和累積和:

select t1.*,
       count(*) filter (where box_type is distinct from prev_box_type) over (order by time) as count
from (select t1.*,
             lag(box_type) over (order by time) as prev_box_type
      from table1 t1
     ) t1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM