2017-07-28 41 views
1

DB一起使用結果 - 的OracleSQL來命令由總和

create table customer_exercise(
customer_id number, 
exercise_id number, 
cnt number, 
exercise_date date) 

表數據

1000 10 3 17-DEC-15 
1001 20 6 19-DEC-15 
1000 20 2 20-DEC-15 
1003 20 9 20-DEC-15 
1000 20 6 22-DEC-15 
1000 30 10 23-DEC-15 
1001 10 25 10-DEC-15 

是否有可能得到使用SQL結果使得總和(CNT)用於exercise_id 20首先出現在結果集?

select customer_id , exercise_id, sum(cnt) from customer_exercise 
where customer_id in (1000, 1001, 1003) and exercise_id in (20) 
group by customer_id, exercise_id order by sum(cnt) 

1001 20 6 
1000 20 8 
1003 20 9 


select customer_id , exercise_id, sum(cnt) from customer_exercise 
where customer_id in (1000, 1001, 1003) and exercise_id not in (20) 
group by customer_id, exercise_id order by sum(cnt) 

1000 10 3 
1000 30 10 
1001 10 25 

我所試圖做的是一個SQL合併上述兩個查詢的結果。是否有可能編寫一個單一的SQL來獲取如下的結果集?

1001 20 6 
1000 20 8 
1003 20 9 
1000 10 3 
1000 30 10 
1001 10 25 

回答

1

我認爲這將是:

select customer_id , exercise_id, sum(cnt) 
from customer_exercise 
where customer_id in (1000, 1001, 1003) 
group by customer_id, exercise_id 
order by (case when exercise_id in (20) then 1 else 2 end), sum(cnt) 
+0

非常感謝你。 – rayne