简体   繁体   中英

SQL query compare value with average of similiar records

The table has 3 columns : Category, Value(int), Date

What I want the SQL query to do is check for each record belonging to a specific category, if the value lies within a specific tolerance range (say t) of the average of value over last 100 records which have the same weekday (monday, tuesday, etc) and same category as that of the concerned record.

I was able to implement this partially, as I know the Category before hand, but the weekday depends on the record which is queried. Also, currently I am just checking if the value is greater than the average, instead of which I need to check if it lies within a certain tolerance.

SELECT Value, Date, 
CASE WHEN 
    value > (SELECT AVG(value) FROM Table WHERE Category = 'CategoryX' and Date BETWEEN current_date - 700 and current_date - 1) THEN 1 
    ELSE 0 
    END AS check_avg
FROM Table
WHERE Category = 'CategoryX'

Sample :

Category Value Date
CategoryX 5000 2022-06-29
CategoryX 4500 2022-06-27
CategoryX 1000 2022-06-22
CategoryY 4500 2022-06-15
CategoryX 2000 2022-06-15
CategoryX 3000 2022-06-08

Expected Result : Value in Record with today's date : 5000. Average of values in records with same weekday and same category : 1000 + 2000 + 3000 / 3 = 2000. If tolerance is 50%, then allowed value should be between 1000 - 3000. So result should be 0

Validate that in both queries you are evaluating the same category and same weekday. Then sort the values that will be used to compute the average by date, and getting only the inmediate previous 100 records. Finally, check the difference between current value and average is below the tolerance interval epsilon.

SELECT Value, Date, 
CASE WHEN 
    ABS(value - (SELECT AVG(Value) FROM (SELECT TOP 100 Value FROM Table WHERE Category = t.Category and DATEPART(WEEKDAY, Date)=DATEPART(WEEKDAY, t.Date) AND Date <= t.Date ORDER BY Date DESC ))) < epsilon THEN 1 
    ELSE 0 
    END AS check_avg
FROM Table t
WHERE Category = 'CategoryX'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM