SELECT p.Distributor,
SUM(r.SalesVolume) AS Sales,
CAST(( ( CAST(SUM(r.SalesVolume) AS DECIMAL(14, 4)) / (SELECT SUM(r.SalesVolume)
FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId
WHERE p.Distributor IN( 'TF1', 'WARNER', 'GAUMONT', 'PATHE',
'STUDIOCANAL', 'M6SND', 'FRANCETV' )
AND p.VODEST IN ( 'EST' )
AND p.ContentFlavor IN ( 'HD' )) ) * 100 ) AS DECIMAL(20, 2)) AS MarketSharesVolume
FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId
WHERE p.Distributor IN ( 'TF1', 'WARNER', 'GAUMONT', 'PATHE',
'STUDIOCANAL', 'M6SND', 'FRANCETV' )
AND p.VODEST IN ( 'EST' )
AND p.ContentFlavor IN ( 'HD' )
GROUP BY p.Distributor;
以上查询肯定不会很漂亮。基本上,如果您注意到子查询中的WHERE
条件,并且主查询是相似的。有没有办法我可以将它们组合起来以减少此查询的大小。还有其他地方我可以尝试减少此查询的大小?
寻找建议。
答案 0 :(得分:2)
您可以使用SUM ... OVER()
上的SUM
来计算总计。
SELECT p.Distributor,
SUM(r.SalesVolume) AS Sales,
CAST(( ( CAST(SUM(r.SalesVolume) AS DECIMAL(14, 4)) / SUM(SUM(r.SalesVolume))
OVER() ) * 100 ) AS DECIMAL(20, 2)) AS MarketSharesVolume
FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId
WHERE p.Distributor IN ( 'TF1', 'WARNER', 'GAUMONT', 'PATHE',
'STUDIOCANAL', 'M6SND', 'FRANCETV' )
AND p.VODEST IN ( 'EST' )
AND p.ContentFlavor IN ( 'HD' )
GROUP BY p.Distributor;