簡體   English   中英

SQL:是否有查詢只在字段中增加+1時才返回記錄?

[英]SQL: is there a query that returns records only when there is an increment of +1 in a field?

樣本表

你好。 我正在尋找一個僅返回“numoflaptop”字段增加的情況的查詢。 我想確定購買任何額外筆記本電腦的家庭。

最終結果應該只有 2 條記錄 'family1, purchase, 3' 和 'family4, purchase, 3'

family2 不包括在結果中,因為它減少了 1,而 family3 不包括在內,因為 numoflaptop 字段沒有變化。

提前致謝。

我正在使用 Teradata

使用窗口函數計算筆記本電腦的變化並識別最近的訪問。 然后將它們用作過濾器。

Select customer, visit_date
From (
    Select customer, visit_date,
       numoflaptop - ifnull(lag(numoflaptop) Over (Group by customer Order By visit_date),0) as laptopchanges,
       Row_number() Over (Group By customer Order By visit_date desc) as latest visit
    )
Where latest_visit=1 and laptopchanges=1

您沒有告訴我們您使用的是哪個數據庫管理器,因此 ifnull function 在您的中可能會以不同的方式命名。 例如,在 Oracle 中,同樣的 function 稱為 nvl。

使用LAG查看上一行的值:

select customer, visit_date, reason, numoflaptop
from
(
  select
    customer, visit_date, reason, numoflaptop,
    lag(numoflaptop) over (partition by customer order by visit_date) as prev
  from mytable
) where numoflaptop > prev
order by customer, visit_date;

暫無
暫無

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

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