表名是SALES哪些產品的銷售額在逐年增加?
**PROD_ID** **YEAR** **QUANTITY**
P1 2012 50
P1 2013 40
P1 2014 30
P2 2012 20
P2 2013 30
P2 2014 40
輸出應該是P2但如何..?
表名是SALES哪些產品的銷售額在逐年增加?
**PROD_ID** **YEAR** **QUANTITY**
P1 2012 50
P1 2013 40
P1 2014 30
P2 2012 20
P2 2013 30
P2 2014 40
輸出應該是P2但如何..?
這個怎麼樣?
select prod_id
from sales
group by prod_id
having (sum(case when year = 2014 then quantity else 0 end) >
sum(case when year = 2012 then quantity else 0 end)
);
我的輸出應該只有P2,因爲產品P2銷售增加,如果你檢查我的表數據 –
根據你的數據看起來總是比較2012年的數據和2014年的數據。戈登的答案是這樣做的,並且也將P1排除在輸出之外。我認爲我們不知道你在找什麼。 – shawnt00
@ shawnt00..'increasing年明智的問題說..所以我認爲應該有每年增加 –
一個稍微複雜的方法來完成這與cte
s。
with diff as (
select prod_id ,
case when quantity - nvl(lag(quantity) over(partition by prod_id order by yr),0) > 0
then 1 else 0 end as df
from sales
)
,totdiff as (select prod_id, sum(df) totdf from diff group by prod_id)
, totals as (select prod_id, count(*) cnt from sales group by prod_id)
select d.prod_id
from totdiff d join totals t on t.prod_id = d.prod_id and d.totdf = t.cnt
編輯:由@ shawnt00在comments..the查詢建議可以簡化爲
with diff as (
select prod_id ,
case when quantity - nvl(lag(quantity) over(partition by prod_id order by yr),0) > 0
then 1 else 0 end as df
from sales
)
select prod_id
from diff
group by prod_id
having count(*) = sum(df)
僅僅通過prod_id總結(df)= count(*)'來從差異組中說'比較清楚嗎?我想知道你是否有理由這樣做,加入。 – shawnt00
是啊..它會是相同的,實際上幾行代碼較小..但我更喜歡寫這種方式更好地理解..也包括你的建議.. @ shawnt00 –
非常感謝你.. –
是否每年都在增加或僅在最終結果? –
只有最終結果,因爲如果你檢查產品P2的數量,那麼它增加一年,所以我的輸出應該是P2 –