用于标识超出容差值的SQL

时间:2009-12-30 22:47:27

标签: sql sql-server

我有一个具有以下结构的数据库表 -

Week_End      Sales 
2009-11-01    43223.43 
2009-11-08     4324.23 
2009-11-15    64343.23 
... 

我想要的是一个SQL语句,它将采用开始日期和结束日期,并识别该期间内销售数字高于或低于该期间平均销售额的3%以上的所有行。因此,针对上述数据运行,它将返回 -

Week_End       Sales 
2009-11-08     4324.23 

我正在使用SQL Server 2008,顺便说一句。

3 个答案:

答案 0 :(得分:4)

注意:示例中的平均值为37297,因此表中的所有三个值最终都超出了容差范围。

;with Weeks as --narrows the range to the provided dates
(
    select * from YourTable 
    where Week_End between @StartDate and @EndDate
),
PercentOff as 
(
    select week_end, sales, abs((a.avg - sales)/a.avg) as pct
    from Weeks
    cross join (select avg(sales) as avg from Weeks) a
)
select * from PercentOff where pct >= .03

答案 1 :(得分:2)

这样的事情应该有效,必要时替换你的日期或参数

SELECT [Week_End]
      ,[Sales]
  FROM [MyTable]
  WHERE [Week_End] BETWEEN '2009-12-01' AND '2009-12-31' AND 
  Notional NOT BETWEEN 
  .97 *
      ( SELECT AVG(Sales) 
        FROM [MyTable]
        WHERE [Week_End] BETWEEN '2009-12-01' AND '2009-12-31')
  AND
  1.03 *(SELECT AVG(Sales) 
        FROM [MyTable]
        WHERE [Week_End] BETWEEN '2009-12-01' AND '2009-12-31')

答案 2 :(得分:1)

我认为你可以在没有使用分析函数的自联接的情况下完成它。不过,我手边没有SQL Server 2008来测试它。试试这个:

SELECT *
FROM (SELECT [Week_End]
           , [Sales]
           , AVG([Sales]) OVER() AS [Avg_Sales]
      FROM [MyTable]
      WHERE [Week_End] BETWEEN '2009-12-01' AND '2009-12-31') AS s
WHERE ABS(([Sales] - [Avg_Sales])/[Avg_Sales]) >= 0.03