Sql趋势线由部门组成

时间:2016-10-14 13:07:11

标签: sql sql-server tsql

我使用如下使用以下链接在报表上创建sql趋势线的示例。

https://www.mssqltips.com/sqlservertip/3432/add-a-linear-trendline-to-a-graph-in-sql-server-reporting-services/

我已经全力以赴,但我也想通过部门来解决这个趋势。然而,它只是将所有数据合并为一个最终值,我认为下面的代码部分需要更改以计算我添加的每个部门的总和,但我最好如何做到这一点?

-- calculate sample size and the different sums
SELECT
  @sample_size = COUNT(*)
 ,@sumX   = SUM(ID)
 ,@sumY   = SUM([OrderQuantity])
 ,@sumXX   = SUM(ID*ID)
 ,@sumYY   = SUM([OrderQuantity]*[OrderQuantity])
 ,@sumXY   = SUM(ID*[OrderQuantity])
FROM #Temp_Regression;

-- output results
SELECT
  SampleSize   = @sample_size  
 ,SumRID    = @sumX   
 ,SumOrderQty   =@sumY   
 ,SumXX    = @sumXX   
 ,SumYY    = @sumYY   
 ,SumXY    = @sumXY;

然后使用这些变量计算出趋势线:

-- calculate the slope and intercept
SET @slope = CASE WHEN @sample_size = 1
    THEN 0 -- avoid divide by zero error
    ELSE (@sample_size * @sumXY - @sumX * @sumY) / (@sample_size * @sumXX - POWER(@sumX,2))
    END;
SET @intercept = (@sumY - (@slope*@sumX)) / @sample_size;

1 个答案:

答案 0 :(得分:0)

您需要在SELECT&中添加GROUP BY列。 SELECT departments, SampleSize = Count(*), SumRID = Sum(ID), SumOrderQty = Sum([OrderQuantity]), SumXX = Sum(ID * ID), SumYY = Sum([OrderQuantity] * [OrderQuantity]), SumXY = Sum(ID * [OrderQuantity]) FROM #Temp_Regression GROUP BY departments

slope

以下是计算intercept&的简便方法。所有部门都;WITH cte AS (SELECT departments, sample_size = Count(*), sumX = Sum(ID), sumY = Sum([OrderQuantity]), sumXX = Sum(ID * ID), sumYY = Sum([OrderQuantity] * [OrderQuantity]), sumXY = Sum(ID * [OrderQuantity]) FROM #Temp_Regression GROUP BY departments), slope AS (SELECT departments, Sample_Size, sumX, sumY, slope = CASE WHEN sample_size = 1 THEN 0 -- avoid divide by zero error ELSE ( sample_size * sumXY - sumX * sumY ) / ( sample_size * sumXX - Power(sumX, 2) ) END FROM cte) SELECT departments, slope, intercept = ( sumY - ( slope * sumX ) ) / sample_size FROM slope

{{1}}