![](/img/trans.png)
[英]Compare the values within the same column against other columns in SQL Server
[英]Dividing within a column based on values of other columns in SQL Server
解決這個問題有些麻煩。
store key promotion key sales year average weekly sales *Desired Output Column*
1 1 2007 100 1 (100 / by itself)
1 1 2008 120 1 (120 / by itself)
1 2 2008 240 2 (240 / 120)
1 3 2007 50 0.5 (50 / 100)
1 4 2007 70 0.7 (70 / 100)
1 5 2007 80 0.8 (80 / 100)
1 3 2008 180 1.5 (180 / 120)
2 1 2009 150 1 (150 / by itself)
2 2 2009 200 1.3 (200 / 150)
2 3 2007 300 Null (no baseline value in 2007)
每個商店關鍵字和銷售年份都有一個由促銷關鍵字 1 表示的基准值。所有其他促銷關鍵字反映了我想要划分為相同商店關鍵字和銷售年份的基准值的條目。
因此,在上面的示例中,我希望所有帶有商店關鍵字 1 和 2007 年的條目除以該年份和商店的基准值(即,同一商店關鍵字 1 和 2007 年銷售年份的促銷關鍵字 1)。 類似地,所有具有商店關鍵字 1 和 2008 年的條目除以該年份的基准值(商店 1 的促銷關鍵字 1 和銷售年份 2008)。 同樣,對於商店 2,我希望促銷密鑰 2 的商店密鑰 2 和 2009 年除以基線值(促銷密鑰 1、商店密鑰 2 和 2009 年)。 由於 2007 年商店密鑰 2 沒有基線值(促銷密鑰 1),因此該條目將產生一個空值。
我想你想要:
select t.*,
(avgweeklysales * 1.0 /
max(case when promotionkey = 1 then avgweeklysales end) over (partition by storekey, salesyear)
) as desired_output
from t;
這與 Gordon 的想法非常相似,但我使用了FIRST_VALUE
:
WITH YourTable AS(
SELECT V.StoreKey,
V.PromotionKey,
V.SalesYear,
V.AvgSales
FROM (VALUES(1,1,2007,100),
(1,1,2008,120),
(1,2,2008,240),
(1,3,2007,50),
(1,4,2007,70),
(1,5,2007,80),
(1,3,2008,180),
(2,1,2009,150),
(2,2,2009,200),
(2,3,2007,300))V(StoreKey,PromotionKey,SalesYear,AvgSales))
SELECT YT.StoreKey,
YT.PromotionKey,
YT.SalesYear,
YT.AvgSales,
(YT.AvgSales * 1.) / FIRST_VALUE(CASE YT.PromotionKey WHEN 1 THEN YT.AvgSales END) OVER (PARTITION BY YT.StoreKey, YT.SalesYear ORDER BY YT.PromotionKey) AS DesiredColumn
FROM YourTable YT
ORDER BY YT.StoreKey,
YT.PromotionKey,
YT.SalesYear;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.