我正在尝试查找影片ID返回的迟到次数占总回报的百分比。
我尝试使用with子句创建列,但是不允许在select语句中使用我创建的列
;with totalrentals as
(
select totalrentals = count(*), f.film_id , f.title
from film f
inner join inventory i on i.film_id = f.film_id
inner join rental r on r.inventory_id = i.[inventory_id]
group by f.film_id , f.title)
, laterentals as (
select i.film_id, f.title,r.return_date,duedate= (r.rental_date+f.rental_duration)
from rental r
inner join inventory i on r.inventory_id = i.inventory_id
inner join film f on f.film_id = i.film_id
where r.return_date > (r.rental_date+f.rental_duration)
group by i.film_id,f.title,r.rental_date+f.rental_duration, r.return_date
),
lr as
(
select Laterentals = count(*), f.film_id , f.title
from laterentals
inner join film f on laterentals.film_id = f.film_id
group by f.film_id, f.title
)
select f.film_id, f.title, lr.laterentals ,tr.totalrentals ,pctlate = (lr.Laterentals /tr.totalrentals)*100
from film f
inner join lr on lr.film_id = f.film_id
inner join totalrentals tr on tr.film_id = f.film_id
inner join inventory i on i.film_id = f.film_id
inner join rental r on r.inventory_id = i.inventory_id
group by f.film_id , f.title, lr.laterentals , tr.totalrentals
order by f.film_id asc
期望报告输出延迟的回报占总回报的百分比
相反,所有pctlate值= 0
Film_ID Title Laterentals Totalrentals pctlate
1 ACADEMY DINOSAUR 7 23 0
2 ACE GOLDFINGER 5 7 0
答案 0 :(得分:1)
似乎字段lr.Laterentals
和tr.totalrentals
是INT
的类型。乘以1.0
并将其转换为DECIMAL
select f.film_id, f.title, lr.laterentals ,tr.totalrentals ,pctlate =
CAST(
( (lr.Laterentals * 1.0) / (tr.totalrentals * 1.0)) * 100
AS DECIMAL(18, 3))
from film f
OR:
select f.film_id, f.title, lr.laterentals ,tr.totalrentals ,pctlate =
CAST(
( CAST(lr.Laterentals AS DECIMAL(18,3)) / (CAST(tr.totalrentals AS DECIMAL 18,3 )))
* 100
AS DECIMAL(18, 3))
from film f
当数据类型为INT
时,您将获得0。如果在除法中仅使用整数,则将获得整数除法。另外,INT
没有余数,但是DECIMAL
有余数。但是,如果至少有一个数字为decimal
或其他类型的余数,则将得到浮点除法
让我展示一个例子:
SELECT (1/2)
输出:0
SELECT ((1 * 1.0) / 2)
输出:0.500000