我手头的任务是"编写一个SQL语句来查找为每个分支中的每个屏幕安排的会话数。显示屏幕详细信息(分支和屏幕的ID)及其对应的会话数。使用branchid和会话数执行多级排序。"
SELECT SCREENID, BRANCHID
FROM SCREEN NATURAL JOIN SESSIONS;
表格屏幕:
---------------------------------------
ScreenID | BranchID | Screencapacity
---------------------------------------
S1 | B1 | 120
S1 | B2 | 185
S2 | B1 | 230
S2 | B4 | 165
S2 | B3 | 185
S1 | B3 | 210
S2 | B4 | 170
S2 | B1 | 150
S3 | B2 | 135
S1 | B4 | 128
---------------------------------------
表会话:
+-----------+----------+----------+---------+-------------+--------------+
| SESSIONID | BRANCHID | SCREENID | MOVIEID | SESSIONDATE | SESSIONPRICE |
+-----------+----------+----------+---------+-------------+--------------+
| SS01 | B1 | S1 | M1 | 03-MAY-16 | 12.5 |
| SS03 | B1 | S2 | M2 | 03-MAY-16 | 12.67 |
| SS09 | B2 | S3 | M4 | 13-MAY-16 | 17.9 |
| SS04 | B4 | S2 | M4 | 13-MAY-16 | 14.56 |
| SS07 | B4 | S2 | M3 | 14-MAY-16 | 21.78 |
| SS05 | B3 | S2 | M5 | 23-MAY-16 | 14.56 |
| SS06 | B3 | S1 | M5 | 03-JUN-16 | 16.32 |
| SS02 | B2 | S1 | M2 | 04-JUN-16 | 19.45 |
| SS10 | B4 | S1 | M3 | 06-JUN-16 | 16.37 |
| SS08 | B1 | S2 | M2 | 06-JUN-16 | 16.82 |
+-----------+----------+----------+---------+-------------+--------------+
我完全迷失了,不知道从哪里开始这个问题
答案 0 :(得分:1)
select screenid, branchid, count(1) as no_of_sessions
from screen A
join session B
on B.screenid = A.screenid
and B.branchid = A.branchid
group by screenid, branchid
order by branchid, no_of_sessions
;
首先,您加入screenid
和branchid
上的两个表格。然后,您按group by
和screenid
将已加入的数据汇总(branchid
)到组,并简单地计算每个组中的行数(count(1)
)。然后,按branchid
和结果中的会话数(no_of_sessions
)对结果进行排序。
享受!