DB - Oracle。所有約束被省略。在sql中結合等級和總和
create table customer (cid number(10), cname varchar(50));
create table exercise (eid number(10), ecode varchar(2), score number(2));
-- mapping table
create table customer_exercise (cid number(10), eid number(10), cnt number(10))
Customer table
cid cname
100 e1
200 e2
300 e3
400 e4
Exercise table
eid ecode score
1 c1 5
2 c2 10
3 c3 6
4 c4 3
Customer_Exercise
cid eid count
100 1 2
200 2 5
100 2 3
300 4 10
SQL檢索總數 -
SELECT c.cid
,e.eid
,COALESCE(SUM(ce.cnt), 0) AS total_cnt
FROM customer c
CROSS JOIN exercise e
LEFT JOIN customer_exercise ce
ON ce.cid = c.cid
AND ce.eid = e.eid
WHERE c.cid IN (100, 200, 300)
AND e.eid IN (1, 2)
GROUP BY c.cid, e.eid
ORDER by c.cid
結果 -
c.cid e.eid total_cnt
100 1 2
100 2 3
200 1 0
200 2 5
300 1 0
300 2 0
SQL來計算排名爲每個客戶爲
select cid , RANK() OVER (ORDER BY sum(total_score) desc) as rank from
(
SELECT c.cid as cid
,e.eid
,COALESCE(SUM(ce.cnt), 0) AS total_cnt
, COALESCE(SUM(ce.cnt), 0) * e.score as total_score
FROM customer c
CROSS JOIN exercise e
LEFT JOIN customer_exercise ce
ON ce.cid = c.cid
AND ce.eid = e.eid
WHERE c.cid IN (100, 200, 300)
AND e.eid IN (1, 2)
GROUP BY c.cid, e.eid, e.score
)
GROUP BY cid
ORDER BY rank
結果 -
c.cid rank
200 1
100 2
300 3
是否有可能使用一個查詢而不是上述兩個查詢得到結果集?我期待將上述兩個查詢的結果合併爲一個。預期結果發佈如下。
預期的結果 - 三代表的
c.cid e.eid total_cnt rank
200 1 0 1
200 2 5 1
100 1 2 2
100 2 3 2
300 1 0 3
300 2 0 3
不要使用像'r ank「作爲列名/別名!使用'rnk'或'rk'或類似的; 'rank'是一個函數的名字。然後:在這個上下文中使用的'dense_rank()'將起作用,如果行列不同的話。然而,如果有兩個'cid'並列爲最高分,那麼使用'rank'而不是'dense_rank'的OP查詢將產生排名1,1,3。'dense_rank'將產生1,1,1 ,1,2,2(由於交叉連接,每個dense_rank重複)。這與OP的要求不一樣。 – mathguy
謝謝@mathguy –