DB - Oracle. All restrictions omitted.
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 to get the total -
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
Result -
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 to calculate the rank for each client -
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
Result -
c.cid rank
200 1
100 2
300 3
Is it possible to get a result set with one query instead of the two above? I am looking to combine the result of the above two queries into one. The expected result will be published below.
Expected Result -
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