Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PostgreSQL:查找租用电影总数的百分比_Postgresql - Fatal编程技术网

PostgreSQL:查找租用电影总数的百分比

PostgreSQL:查找租用电影总数的百分比,postgresql,Postgresql,下面的代码给出了以下结果 Early: 7738 Late: 6586 On Time: 1720 我如何进一步添加第三列来查找百分比 以下是ERD和数据库设置的链接: 具有 t1 像 选择*,日期部分为“天”,返回日期-租赁日期为租赁天数 租金 , t2 像 选择租赁期限、租赁天数、, 租赁持续时间>租赁天数然后“提前”的情况 当租赁时间=租赁天数时,则“准时” 否则“迟到” 结束为租赁\退货\状态 来自胶片f,库存i,t1 其中f.film_id=i.film_id,t1.inventor

下面的代码给出了以下结果

Early: 7738
Late: 6586
On Time: 1720
我如何进一步添加第三列来查找百分比

以下是ERD和数据库设置的链接:

具有 t1 像 选择*,日期部分为“天”,返回日期-租赁日期为租赁天数 租金 , t2 像 选择租赁期限、租赁天数、, 租赁持续时间>租赁天数然后“提前”的情况 当租赁时间=租赁天数时,则“准时” 否则“迟到” 结束为租赁\退货\状态 来自胶片f,库存i,t1 其中f.film_id=i.film_id,t1.inventory_id=i.inventory_id 选择租赁\归还\状态,将*计为总租赁\电影 从t2开始 按1分组 按2描述订购; 使用a获取计数列sumcount*over的和,然后将计数除以该计数*/sumcount*over。乘以100使之成为一个百分比

psql (12.1 (Debian 12.1-1))
Type "help" for help.

testdb=# CREATE TABLE faket2 AS (
SELECT 'early' AS rental_return_status UNION ALL
SELECT 'early' UNION ALL
SELECT 'ontime' UNION ALL
SELECT 'late');
SELECT 4
testdb=# SELECT
  rental_return_status,
  COUNT(*) as total_films_rented,
  (100*count(*))/sum(count(*)) over () AS percentage
FROM faket2
GROUP BY 1
ORDER BY 2 DESC;
 rental_return_status | total_films_rented |     percentage      
----------------------+--------------------+---------------------
 early                |                  2 | 50.0000000000000000
 late                 |                  1 | 25.0000000000000000
 ontime               |                  1 | 25.0000000000000000
(3 rows)

您可以将窗口函数与一个CTE表(而不是2个)一起使用:

WITH raw_status AS (
  SELECT rental_duration - DATE_PART('day', return_date - rental_date) AS days_remaining
    FROM rental r
    JOIN inventory i ON r.inventory_id=i.inventory_id
    JOIN film f on f.film_id=i.film_id
  )
SELECT CASE WHEN days_remaining > 0 THEN 'Early'
            WHEN days_remaining = 0 THEN 'On Time'
            ELSE 'Late' END AS rental_status,
       count(*),
       (100*count(*))/sum(count(*)) OVER () AS percentage
FROM raw_status
GROUP BY 1;
 rental_status | count |     percentage      
---------------+-------+---------------------
 Early         |  7738 | 48.2298678633757168
 On Time       |  1720 | 10.7205185739217153
 Late          |  6586 | 41.0496135627025679
(3 rows)
披露:我为