sql求連續值問題

一. 找出表test1中tflag字段連續出現3次及以上爲1的行

1.png
思路:1. 對行進行編號,2. 對相鄰三行進行求和算出值作爲sumflag,3. 如果值爲3,則該行以及接下來的2行都輸出出來,通過自關聯解決。

WITH tmp AS (
  SELECT tday, tflag, 
         row_number() over(partition by null order by tday) as rn, -- 對錶進行排序,並編rownumber
         sum(tflag) over (partition by null order by tday rows between current row and 2 following) sumflag -- 對字段tflag往下2行求和
    FROM test1) 
SELECT tday, tflag 
  FROM tmp a 
 WHERE EXISTS (SELECT 1 FROM tmp b WHERE a.rn >= b.rn AND a.rn <= b.rn + 2 AND b.sumflag = 3); -- 對錶進行關聯取值

2.png

二. 找出表test2中price字段連續上漲3次及以上的行。

3.png
思路:這題較上一題有點難度,連續上漲3次,也就是至少輸出4行。需要用到錯位函數,相鄰行相減。

  1. 對行進行編號,2. 對相鄰行相減,3. 對減法的flag進行求和,4. 自關聯
WITH tmp1 AS (
  SELECT tday, price, 
         row_number() over(partition by null order by tday) as rn, -- 對錶進行排序,並編rownumber
         case when (price - lag(price) over(partition by null order by tday) >0) then 1 else 0 end as tflag -- 對上一行相減 
    FROM test2),
     tmp2 AS (  
  SELECT rn 
    FROM (SELECT rn, 
                 sum(tflag) over (partition by null order by tday rows between current row and 2 following) sumflag 
            FROM tmp1) x 
   WHERE sumflag = 3) -- 過濾出連續3次上漲的第1次上漲的行 
SELECT tday, price FROM tmp1 
 WHERE EXISTS (SELECT 1 FROM tmp2 WHERE tmp1.rn >= tmp2.rn - 1 AND tmp1.rn <= tmp2.rn + 2); -- 需要找出前1行和後2行組成連續的4行

4.png

附件:

CREATE TABLE test1 (
  tday varchar(10),
  tflag int 
);

INSERT INTO test1 VALUES ('1201',0),('1202',1),('1203',0),('1205',0),('1208',1),('1209',1),('1210',1),('1213',1),('1215',0),('1216',0),('1219',1),('1220',1),('1222',0),('1223',1),('1224',1),('1225',1),('1226',0),('1227',0),('1228',1),('1229',1),('1230',0),('1231',1);

CREATE TABLE test2 (
  tday varchar(10),
  price int
);

INSERT INTO test2 VALUES ('1201',10),('1203',20),('1204',17),('1205',15),('1207',23),('1208',26),('1209',29),('1210',11),('1211',9),('1213',5),('1214',7),('1215',15),('1217',15),('1218',13),('1219',11),('1220',9),('1221',10),('1223',30),('1224',40),('1225',50),('1227',21),('1228',40),('1229',30),('1230',11);

我一邊聽着鳳凰傳奇的動次打次,一邊去想sql,這歌真提神!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章