2017-09-08 52 views
-2

首先,我需要從2016年的前3個月得到體育和音樂部門TotalPrice的總和,其次,我需要從2016年的所有TotalPrice總和中得出結果所有部門,第三 - 我需要得到的第一個結果除以總價的總和來自多年。 所有這一切在相同的查詢!我該如何查詢一些利潤?

謝謝!

該表名爲Sales,屬性爲:S_id,日期,部門,totalPrice。

THIS IS MY CHRY:

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" 
+3

添加表定義,樣本表數據和預期結果(作爲格式化文本,而不是圖像)。並向我們​​展示您當前的查詢嘗試。 – jarlh

+0

你對E/R模型有什麼想法嗎? – Frank

+0

該表名爲Sales,屬性爲:S_id,日期,部門,totalPrice。 THIS IS MY CHRY:SELECT SUM(TotalPrice)作爲sportMusic,sportMusic /總和(TotalPrice) 銷售 凡(部門= 「MUSIC」 或部門= 「SPORT」) 和日之間的「2016/01/01「和」2016/03/31「 – user3374271

回答

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;