這與我在這里嘗試回答的一個問題有關:識別具有下降趨勢 SQL 的用戶。
鑒于以下起始位置:
WITH
tbl (customer, purchasedate, quantity) AS (
SELECT * FROM VALUES
('Lucus', '9/1/2021', 5),
('Lucus', '9/10/2021', 6),
('Lucus', '9/18/2021', 10)
)
SELECT
customer, array_agg(quantity) from tbl group by customer
有沒有辦法匯總客戶并查看價值是否總是增加或減少?例如,在上面,我們會得到一個總是增加的陣列(如果有幫助?):
CUSTOMER ARRAY_AGG(QUANTITY)
Lucus [ 5, 6, 10 ]
是否有一個函式可以執行以下操作:
>>> bool(reduce(lambda x,y: x if x>y else False, [3,2,4]))
False
>>> bool(reduce(lambda x,y: x if x>y else False, [3,2,1]))
True
uj5u.com熱心網友回復:
這會查看系列中的每對相鄰數字,并檢測是否有任何差異為負:
with data as (
select customer,
quantity
- lag(quantity)
over (partition by customer order by purchasedate) as diff
from tbl
)
select customer,
case when
count(case when diff < 0 then 1 end) < count(diff)
then 'Y' else 'N' end as Increasing
from data
group by customer
如果您也有興趣檢測單調遞減的系列,那么您可以使用類似的邏輯。
https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=0e64219f851a1409d7623169234c644c
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/327540.html
標籤:sql
上一篇:重新編譯已更改的表
