按 SQL 中的计数计算排序
Order by the Compute of Count in SQL
您好,我得到了我正在寻找的结果,但是,我想按计算的计数对其进行排序。任何人都有任何想法。
Break on 'Movie Title' skip 2
COMPUTE COUNT Label '# of Times Rented' of "Customer" on "Movie Title"
select film_title "Movie Title", star_rating "Customer Rating",
name "Customer"
from TITLE t join RENTAL r on(t.TITLE_NO = r.TITLE_NO)
join CUSTOMER c on(r.CUSTOMER_NO = c.CUSTOMER_NO)
order by 1,3;
一种方法是使用 window 函数根据该值计算和排序。
以下按 n
降序排列结果,但不包括 n
在最终 SELECT
列表中。
我保留了您的原始订单标准以打破任何联系。
Break on 'Movie Title' skip 2
COMPUTE COUNT Label '# of Times Rented' of "Customer" on "Movie Title"
WITH cte1 AS (
SELECT film_title, star_rating
, name
, COUNT(*) OVER (PARTITION BY t.title_no) AS n
FROM ddr_title t
JOIN rental r
ON t.title_no = r.title_no
JOIN customer c
ON r.customer_no = c.customer_no
)
SELECT film_title "Movie Title", star_rating "Customer Rating"
, name "Customer"
FROM cte1
ORDER BY n DESC, 1, 3
;
示例结果:
Movie Title Customer Rating Customer
------------------------------ --------------- ------------------------------
title1 3 Customer1
3 Customer1
3 Customer1
3 Customer2
****************************** ------------------------------
# of Times Rented 4
title3 1 Customer1
1 Customer2
****************************** ------------------------------
Movie Title Customer Rating Customer
------------------------------ --------------- ------------------------------
# of Times Rented 2
title2 2 Customer2
****************************** ------------------------------
# of Times Rented 1
7 rows selected.
您好,我得到了我正在寻找的结果,但是,我想按计算的计数对其进行排序。任何人都有任何想法。
Break on 'Movie Title' skip 2
COMPUTE COUNT Label '# of Times Rented' of "Customer" on "Movie Title"
select film_title "Movie Title", star_rating "Customer Rating",
name "Customer"
from TITLE t join RENTAL r on(t.TITLE_NO = r.TITLE_NO)
join CUSTOMER c on(r.CUSTOMER_NO = c.CUSTOMER_NO)
order by 1,3;
一种方法是使用 window 函数根据该值计算和排序。
以下按 n
降序排列结果,但不包括 n
在最终 SELECT
列表中。
我保留了您的原始订单标准以打破任何联系。
Break on 'Movie Title' skip 2
COMPUTE COUNT Label '# of Times Rented' of "Customer" on "Movie Title"
WITH cte1 AS (
SELECT film_title, star_rating
, name
, COUNT(*) OVER (PARTITION BY t.title_no) AS n
FROM ddr_title t
JOIN rental r
ON t.title_no = r.title_no
JOIN customer c
ON r.customer_no = c.customer_no
)
SELECT film_title "Movie Title", star_rating "Customer Rating"
, name "Customer"
FROM cte1
ORDER BY n DESC, 1, 3
;
示例结果:
Movie Title Customer Rating Customer
------------------------------ --------------- ------------------------------
title1 3 Customer1
3 Customer1
3 Customer1
3 Customer2
****************************** ------------------------------
# of Times Rented 4
title3 1 Customer1
1 Customer2
****************************** ------------------------------
Movie Title Customer Rating Customer
------------------------------ --------------- ------------------------------
# of Times Rented 2
title2 2 Customer2
****************************** ------------------------------
# of Times Rented 1
7 rows selected.