如何用几个利润进行查询?

时间:2017-09-08 10:03:42

标签: mysql sql

首先,我需要从2016年前3个月获得体育和音乐部门TotalPrice的总和,其次,我需要得到我写的结果,然后再划分为2016年所有TotalPrice的总和来自所有部门,第三 - 我需要将第一个结果除以多年来所有总价格的总和。 所有这一切都在同一个问题上!

谢谢!

名为Sales的表,属性为:S_id,date,department,totalPrice。

这是我的孩子:

Select sum(TotalPrice) as sportMusic, sportMusic/sum(TotalPrice)
From Sales
Where (Department="MUSIC" OR Department="SPORT") and
       DATE BETWEEN "2016/01/01" AND "2016/03/31"

1 个答案:

答案 0 :(得分:0)

您可以在from子句中将查询和另外两个查询用作子查询(也称为“派生表”)。交叉连接三个结果行并使用select子句中的总计。有点像:

select
  ms_2016_q1.total as   ms_2016_q1_total,
  ms_2016_q1.total / all_2016.total as rate_2016,
  ms_2016_q1.total / all_years.total as rate_all
from
(
  select sum(totalprice) as total
  from sales
  where department in ('MUSIC', 'SPORT')
    and date between date '2016-01-01' and date '2016-03-31'
) ms_2016_q1
cross join
(
  select sum(totalprice) as total
  from sales
  where date between date '2016-01-01' and date '2016-12-31'
) all_2016
cross join
(
  select sum(totalprice) as total
  from sales
) all_years;