我正在查询包含电影票的表。数据库包含 380k 行。一行代表电影的放映(哪家电影院,什么时候,有多少票,什么价格等等)。
我需要计算几个总计为每一行:Admissions Paid,Admissions Revenue,Admissions Free和Total Admissions。
对于给定的行,Admissions Paid是该电影的所有门票的总和,直到price>0. 其他 3 列的计算方法类似。
我写了一个查询并创建了一个索引:
SELECT [ID]
,[cinema_name]
,[movie_title]
,[price]
,[quantity]
,[start_date_time]
,* --I need all the columns for reporting
,(select SUM(quantity)
from [movies] i
where i.movie_title=o.movie_title
and i.start_date_time<=o.start_date_time
and price=0) as [Admissions Free]
,(select SUM(quantity)
from [movies] i
where i.movie_title=o.movie_title
and i.start_date_time<=o.start_date_time
and price>0) as [Admissions Paid]
,(select SUM(quantity*price)
from [movies] i
where i.movie_title=o.movie_title
and i.start_date_time<=o.start_date_time
and price>0) …Run Code Online (Sandbox Code Playgroud)