『查詢同一廠商同一料號,如果連續五次無退貨資料就顯示,
但是如果有退貨資料次數就需要重新計算』
這個用到了『判斷是不是連續整數的』用法。
先上全部SQL
declare @in table
(sn int primary key NOT NULL identity(1,1),name varchar(10),category varchar(20),amt int)
declare @out table
(sn int primary key NOT NULL identity(1,1),name varchar(10),category varchar(20),amt int)
insert into @in values ('Liu','01',5000),('Chiu','02',3000),('Chiu','03',3000),('Chiu','04',3000),('Chiu','05',3000),('Liu','02',5000)
insert into @out values ('Chiu','02',5000),('Chiu','05',3000),('Chiu','04',4000),('Liu','02',5000)
;with tt as (
select
*
from (
select ROW_NUMBER() OVER (partition by a.name order by a.name) as g_sn,a.name,a.category,b.name as b_name
from @in a left join @out b on a.name=b.name and a.category = b.category
) a
where b_name is not null
)
select name,min(category),max(category),count(*) as count_val
from (
select name,category,g_sn-sn as cc from (select g_sn,category,name,ROW_NUMBER() over(partition by name order by category) sn from tt)a
)a
group by name,cc
先將他排序,看是哪個單號是沒有退貨的,使用left join抓出來。最後排除掉NULL值,
基本上會長這樣子
g_sn name category b_name
1 Chiu 02 Chiu
2 Chiu 03 NULL
3 Chiu 04 Chiu
4 Chiu 05 Chiu
1 Liu 02 Liu
2 Liu 01 NULL
排除掉NULL後會看到g_sn是有跳號的,所以是不連續,但怎麼判斷有沒有連續?
1 Chiu 02 Chiu
3 Chiu 04 Chiu
4 Chiu 05 Chiu
1 Liu 02 Liu
此時就要靠第二段SQL
select name,category,g_sn-sn as cc from (select g_sn,category,name,ROW_NUMBER() over(partition by name order by category) sn from tt)a
來源:這裡 (此網頁是使用oracle的語法)這邊的用法是 先列出正常累加的sn再跟g_sn相減,會得到一個不是0 就是 1的數值。
Chiu 02 0
Chiu 04 1
Chiu 05 1
Liu 02 1
再根據此值做group 就可以知道這組連續數字是從哪裡到哪裡,然後有幾個。
name (沒有資料行名稱) (沒有資料行名稱) count_val
Chiu 02 02 1
Chiu 04 05 2
Liu 02 02 1
0 意見:
張貼留言