CustID Sequencing Total
2 1 10
4 2 20
3 2 30
4 4 40
5 8 50
我希望选择订单金额> gt = =订单金额的客户,如何实现?
答案 0 :(得分:1)
对于2005,2008版本:
declare @t table(cust int, ord_s int, ord_a int);
insert @t values
(1,1,30), (1,3,40), (2,1,40), (2,6,30), (3,4,15),
(3,7,60),(3,8,50),(4,2,32),(4,5,2),(4,7,4);
with cte as
(
select row_number() over(partition by cust order by ord_s) as rn, *
from @t
)
select c1.cust,
c1.ord_s,
c1.ord_a,
c2.ord_a as prv
from cte as c1 join cte as c2
on c1.cust = c2.cust and c1.rn = c2.rn + 1
where c1.ord_a > c2.ord_a;
听到的想法总是一样的,你应该找到以前的订单,如果你不能使用滞后,你在每个客户中列举订单并加入如上所述的相邻订单,如果你不能使用甚至row_number,你可以搜索最近的值当前这样的人不如:
select tt1.*
from
(
select *,
(select max(t2.ord_s) from @t t2 where t2.cust = t1.cust and t2.ord_s < t1.ord_s) as prv
from @t t1
) tt1
join @t tt2
on tt1.cust = tt2.cust and tt1.prv = tt2.ord_s
where tt1.ord_a > tt2.ord_a;
答案 1 :(得分:0)
使用ANSI标准Array
(
[0] => Some Stuff
[1] => Some more stuff
[2] => Some other stuff
)
功能,您可以选择值增加的所有场合:
lag()
编辑:
对于修订后的问题,您可以使用select t.*
from (select t.*,
lag(amount) over (partition by customer order by order_sequence) as prev_amount
from t
) t
where amount > prev_amount;
。但是,我并不是100%明确的确切逻辑:
first_value()
答案 2 :(得分:0)
DECLARE @Temp table(cust int, ord_seq int, ord_amt int);
insert @Temp values
(1,1,30), (1,3,40), (2,1,40), (2,6,30), (3,4,15),
(3,7,60),(3,8,50),(4,2,32),(4,5,2),(4,7,4);
SELECT
Seq AS SeqNo
,cust AS CustomerID
,ord_seq AS OrderSequence
,ord_amt AS OrderAmount
FROM (
SELECT *,CASE WHEN LAGord_amt IS NULL THEN 0
ELSE 1
END As LAGord_amt1
,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS Seq
,CASE
WHEN ord_amt > LAGord_amt
THEN ord_amt
ELSE 0
END Lagval
FROM (
SELECT *,LAG(ord_amt) OVER (PARTITION BY cust ORDER BY ord_seq) As LAGord_amt
FROM @Temp
) Dt
) Dt2
WHERE Dt2.LAGord_amt1 = 1
AND Lagval <> 0
输出
SeqNo CustomerID OrderSequence OrderAmount
---------------------------------------------
2 1 3 40
6 3 7 60
10 4 7 4