My query gather a technician daily sales data.
select
SUM(O.SUB_TOTAL) AS TOTALSALES,
COUNT(DISTINCT O.ORDER_NO) AS BILLABLEORDERS
FROM ordhdr o
INNER JOIN schedule s ON s.ID_VAL = o.ORDER_NO
WHERE
s.DATE = Convert(varchar(10), GETDATE()-1,121)
AND O.[TYPE] = 'SVC'
However, I also want to get weekly cumulative sales to know whether he is on track or not for his weekly numbers but I struggling transforming the query.
This has to reset for each Sunday or Monday so I cannot use a CurrentDate-7 function.
I don't know how to only look at a CURRENT weeks data using SQL-Server Management Studio.
Look into the 'DatePart' function. You can use it to identify which week out of the year a given date resides in, and it seems to turn over on Sunday. For instance:
datepart(week, '2019-07-06') -- Saturday, returns 27
datepart(week, '2019-07-07') -- Sunday, returns 28
That alone should get you going. However, you can throw in a few more techniques to get all the information in one resultset.
Consider the following ordhdr table:
declare #ordhdr table (
order_no int,
sub_total decimal(8,2),
type varchar(15)
);
insert #ordhdr values
(1, 23.25, 'svc'),
(2, 324.23, 'svc'),
(3, 423.89, 'svc'),
(4, 324.80, 'svc'),
(5, 234.23, 'svc'),
(6, 923.23, 'svc');
... and the following schedule table:
declare #schedule table (id_val int, date date);
insert #schedule values
(1, '2019-07-04'),
(2, '2019-07-04'),
(3, '2019-07-08'),
(4, '2019-07-09'),
(5, '2019-07-09'),
(6, '2019-07-10');
Well, using datepart, datename, cross apply, and grouping sets, you can do this:
select ap.year,
ap.weekOfYear,
dayOfWeek =
case
when ap.weekOfYear is null then '<entire year>'
when ap.dayOfWeek is null then '<entire week>'
else ap.dayOfWeek
end,
s.date,
totalsales = sum(o.sub_total),
billableorders = count(distinct o.order_no)
from #ordhdr o
join #schedule s on s.id_val = o.order_no
cross apply (select
year = datepart(year, s.date),
weekOfYear = datepart(week, s.date),
dayOfWeek = datename(weekday, s.date)
) ap
where o.type = 'svc'
group by grouping sets (
(ap.year, ap.weekOfYear, ap.dayOfWeek, s.date),
(ap.year, ap.weekOfYear),
(ap.year)
)
order by weekOfYear, date
Which will give you daily, weekly, and yearly totals.
Related
I have people that do many multi-day assignments (date x to date Y). I would like to find the date that they completed a milestone e.g. 50 days work completed.
Data is stored as a single row per Assignment
AssignmentId
StartDate
EndDate
I can sum up the total days they have completed up to a date, but am struggling to see how I would find out the date that a milestone was hit. e.g. How many people completed 50 days in October 2020 showing the date within the month that this occurred?
Thanks in advance
PS. Our database is SQL Server.
As mentioned by prwvious comments, it would be much easier to help you if you could provide example data and table structure in order help you answer this question.
However, guessing a simple DB structure with a table for your peolple, your tasks and the work each user completed, you can get the required sum of days by use of a date table (or cte) which contains a entry for each day and the window function SUM with UNBOUNDED PRECEDING. Following an example:
DECLARE #people TABLE(
id int
,name nvarchar(50)
)
DECLARE #tasks TABLE(
id int
,name nvarchar(50)
)
DECLARE #work TABLE(
people_id int
,task_id int
,task_StartDate date
,task_EndDate date
)
INSERT INTO #people VALUES (1, 'Peter'), (2, 'Paul'), (3, 'Mary');
INSERT INTO #tasks VALUES (1, 'Devleopment'), (2, 'QA'), (3, 'Sales');
INSERT INTO #work VALUES
(1, 1, '2019-04-05', '2019-04-08')
,(1, 1, '2019-05-05', '2019-06-08')
,(1, 1, '2019-07-05', '2019-09-08')
,(2, 2, '2019-04-08', '2019-06-08')
,(2, 2, '2019-09-08', '2019-10-03')
,(3, 1, '2019-11-01', '2019-12-01')
;WITH cte AS(
SELECT CAST('2019-01-01' AS DATE) AS dateday
UNION ALL
SELECT DATEADD(d, 1, dateday)
FROM cte
WHERE DATEADD(d, 1, dateday) < '2020-01-01'
),
cteWorkDays AS(
SELECT people_id, task_id, dateday, 1 AS cnt
FROM #work w
INNER JOIN cte c ON c.dateday BETWEEN w.task_StartDate AND w.task_EndDate
),
ctePeopleWorkdays AS(
SELECT *, SUM(cnt) OVER (PARTITION BY people_id ORDER BY dateday ROWS UNBOUNDED PRECEDING) dayCnt
FROM cteWorkDays
)
SELECT *
FROM ctePeopleWorkdays
WHERE dayCnt = 50
OPTION (MAXRECURSION 0)
The solution depends on how you store your data. The solution below assumes that each worked day exists as a single row in your data model.
The approach below uses a common table expression (cte) to generate a running total (Total) for each person (PersonId) and then filters on the milestone target (I set it to 5 to reduce the sample data size) and target month.
Sample data
create table WorkedDays
(
PersonId int,
TaskDate date
);
insert into WorkedDays (PersonId, TaskDate) values
(100, '2020-09-01'),
(100, '2020-09-02'),
(100, '2020-09-03'),
(100, '2020-09-04'),
(100, '2020-09-05'), -- person 100 worked 5 days by 2020-09-05 = milestone (in september)
(200, '2020-09-29'),
(200, '2020-09-30'),
(200, '2020-10-01'),
(200, '2020-10-02'),
(200, '2020-10-03'), -- person 200 worked 5 days by 2020-10-03 = milestone (in october)
(200, '2020-10-04'),
(200, '2020-10-05'),
(200, '2020-10-06'),
(300, '2020-10-10'),
(300, '2020-10-11'),
(300, '2020-10-12'),
(300, '2020-10-13'),
(300, '2020-10-14'), -- person 300 worked 5 days by 2020-10-14 = milestone (in october)
(300, '2020-10-15'),
(400, '2020-10-20'),
(400, '2020-10-21'); -- person 400 did not reach the milestone yet
Solution
with cte as
(
select wd.PersonId,
wd.TaskDate,
count(1) over(partition by wd.PersonId
order by wd.TaskDate
rows between unbounded preceding and current row) as Total
from WorkedDays wd
)
select cte.PersonId,
cte.TaskDate as MileStoneDate
from cte
where cte.Total = 5 -- milestone reached
and year(cte.TaskDate) = 2020
and month(cte.TaskDate) = 10; -- in october
Result
PersonId MilestoneDate
-------- -------------
200 2020-10-03
300 2020-10-14
Fiddle (also shows the common table expression output).
I have an sql table that has transaction history of all the clients. I want to find what is the average difference in time between two transactions.
ClientCode Date
DL2xxx 2016-04-18 00:00:00.000
DL2xxx 2016-04-18 00:00:00.000
E19xxx 2016-04-18 00:00:00.000
E19xxx 2016-04-18 00:00:00.000
E19xxx 2016-04-18 00:00:00.000
JDZxxx 2016-04-18 00:00:00.000
Given above are the first few lines of the table the date given is the date transaction happened. I want to take an average of difference in days when successive transactions happen. Say for a client he makes transactions of Day 1, Day 3, Day 10, and Day 15. So differences are {2, 7, 5} average of which is 4.66. If only one transaction takes place this should be 0.
ClientCode AverageDays
DL2xxx <float_value>
DL2xxx <float_value>
E19xxx <float_value>
This is what the output should look like where each unique client code occurs only once.
You can use a query like below if you table name is T
see live demo
select
ClientCode,
AvgDays =ISNULL(AVG(d),0)
from
(
select
*,
d=DATEDIFF(
d,
dateofT,
LEAD(DateofT) over(
partition by ClientCode
order by DateofT asc ))
from t
)t
group by ClientCode
If Windowing functions aren't available to you, here's an alternative
--CREATE SAMPLE DATA
CREATE TABLE #TMP(ClientID INT, EventDate DATE)
GO
INSERT INTO #TMP VALUES
(1,DATEADD(DD,RAND()*365,'20180101'))
,(2,DATEADD(DD,RAND()*365,'20180101'))
,(3,DATEADD(DD,RAND()*365,'20180101'))
,(4,DATEADD(DD,RAND()*365,'20180101'))
,(5,DATEADD(DD,RAND()*365,'20180101'))
GO 50
--PRE SQL 2012 Compatible
SELECT A.ClientID
,AVG(DATEDIFF(DD,C.EventDate,A.Eventdate)) AS ClientAvg
FROM #TMP A
CROSS APPLY (SELECT ClientID, MAX(EventDate) EventDate FROM #TMP B
WHERE A.ClientID = B.ClientID AND A.EventDate > B.EventDate
GROUP BY ClientID) C
GROUP BY A.ClientID
ORDER BY A.ClientID
You can use LAG() function to compare a date to it's previous date by client, then group by client and calculate the average.
IF OBJECT_ID('tempdb..#Transactions') IS NOT NULL
DROP TABLE #Transactions
CREATE TABLE #Transactions (
ClientCode VARCHAR(100),
Date DATE)
INSERT INTO #Transactions (
ClientCode,
Date)
VALUES
('DL2', '2016-04-18'),
('DL2', '2016-04-19'),
('DL2', '2016-04-26'),
('E19', '2016-01-01'),
('E19', '2016-01-11'),
('E19', '2016-01-12')
;WITH DayDifferences AS
(
SELECT
T.ClientCode,
T.Date,
DayDifference = DATEDIFF(
DAY,
LAG(T.Date) OVER (PARTITION BY T.ClientCode ORDER BY T.Date ASC),
T.Date)
FROM
#Transactions AS T
)
SELECT
D.ClientCode,
AverageDayDifference = AVG(ISNULL(CONVERT(FLOAT, D.DayDifference), 0))
FROM
DayDifferences AS D
GROUP BY
D.ClientCode
Using the observation that the sum of differences within a group is simply the max - min of that group, you can use the simple group by select:
select IIF(COUNT(*) > 1,
(CAST(DATEDIFF(day, MIN(DateofT), MAX(DateofT)) AS FLOAT)) / (COUNT(*) - 1), 0.0)
AS AVGDays, ClientCode
FROM t GROUP BY ClientCode
I have 2 tables name EmployeeInfo and Leave and I am storing the values that which employee have taken which type of leave in month and how many times.
I am trying to calculate the number of leaves of same type but I'm stuck at one point for long time.
IF EXISTS(SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('Leave'))
BEGIN;
DROP TABLE [Leave];
END;
GO
IF EXISTS(SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('EmployeeInfo'))
BEGIN;
DROP TABLE [EmployeeInfo];
END;
GO
CREATE TABLE [EmployeeInfo] (
[EmpID] INT NOT NULL PRIMARY KEY,
[EmployeeName] VARCHAR(255)
);
CREATE TABLE [Leave] (
[LeaveID] INT NOT NULL PRIMARY KEY,
[LeaveType] VARCHAR(255) NULL,
[DateFrom] VARCHAR(255),
[DateTo] VARCHAR(255),
[Approved] Binary,
[EmpID] INT FOREIGN KEY REFERENCES EmployeeInfo(EmpID)
);
GO
INSERT INTO EmployeeInfo([EmpID], [EmployeeName]) VALUES
(1, 'Marcia'),
(2, 'Lacey'),
(3, 'Fay'),
(4, 'Mohammad'),
(5, 'Mike')
INSERT INTO Leave([LeaveID],[LeaveType],[DateFrom],[DateTo], [Approved], [EmpID]) VALUES
(1, 'Annual Leave','2018-01-08 04:52:03','2018-01-10 20:30:53', 1, 1),
(2, 'Sick Leave','2018-02-10 03:34:41','2018-02-14 04:52:14', 0, 2),
(3, 'Casual Leave','2018-01-04 11:06:18','2018-01-05 04:11:00', 1, 3),
(4, 'Annual Leave','2018-01-17 17:09:34','2018-01-21 14:30:44', 0, 4),
(5, 'Casual Leave','2018-01-09 23:31:16','2018-01-12 15:11:17', 1, 3),
(6, 'Annual Leave','2018-02-16 18:01:03','2018-02-19 17:16:04', 1, 2)
My query which I have tried so far look something like this.
SELECT Info.EmployeeName, Leave.LeaveType, SUM(DATEDIFF(Day, Leave.DateFrom, Leave.DateTo)) [#OfLeaves], DatePart(MONTH, Leave.DateFrom)
FROM EmployeeInfo Info, Leave
WHERE Info.EmpID = Leave.EmpID AND Approved = 1
GROUP BY Info.EmployeeName, Leave.LeaveType, [Leave].[DateFrom], [Leave].[DateTo]
And the record like given below
EmployeeName LeaveType #OfLeaves MonthNumber
-------------- ----------------- ----------- -----------
Fay Casual Leave 1 1
Fay Casual Leave 3 1
Lacey Annual Leave 3 2
Marcia Annual Leave 2 1
I want the record to look like this
EmployeeName LeaveType #OfLeaves MonthNumber
-------------- ----------------- ----------- -----------
Fay Casual Leave 4 1
Lacey Annual Leave 3 2
Marcia Annual Leave 2 1
If you don't want to modify existing query due to some constraint, this might work:
Select iq.EmployeeName, iq.LeaveType, SUM(iq.#OfLeaves) as #OfLeaves, iq.MonthNumber
From (
SELECT Info.EmployeeName, Leave.LeaveType, SUM(DATEDIFF(Day, Leave.DateFrom, Leave.DateTo)) [#OfLeaves], DatePart(MONTH, Leave.DateFrom) as MonthNumber
FROM EmployeeInfo Info, Leave
WHERE Info.EmpID = Leave.EmpID AND Approved = 1
GROUP BY Info.EmployeeName, Leave.LeaveType, [Leave].[DateFrom], [Leave].[DateTo]
)iq
group by iq.EmployeeName, iq.LeaveType, iq.MonthNumber
This just need small adjustment with your query in the GROUP BY clause. Instead of grouping them by [Leave].[DateFrom] and [Leave].[DateTo] which causes the row to be separated, you need to group it with the calculated column that uses datepart.
SELECT Info.EmployeeName,
Leave.LeaveType,
SUM(DATEDIFF(Day, Leave.DateFrom, Leave.DateTo)) [#OfLeaves],
DatePart(MONTH, Leave.DateFrom)
FROM EmployeeInfo Info
INNER JOIN Leave
ON Info.EmpID = Leave.EmpID
WHERE Approved = 1
GROUP BY Info.EmployeeName,
Leave.LeaveType,
DatePart(MONTH, Leave.DateFrom) -- <<<< change only this part
Here's a Demo.
I have also modified the syntax into ANSI format.
I have a table with records Holding patrols of guards in SQL Server 2008R2.
Whenever a duty starts a new alert number is created and within this alert number there a patrols with a starting time.
Per 12 hours we can bill a flat rate when at least one patrol has been performed. When under the same alert number the 12 hour range is exceeded, a further flat rate has to be billed.
The calculation of the 12 hours starts with the time of the first patrol.
I tried with a temp table but could not solve it so far.
DECLARE #t1 TABLE (
AlertNo INT,
Starttime SMALLDATETIME,
Endtime SMALLDATETIME
)
INSERT INTO #t1 (AlertNo, Starttime, Endtime)
SELECT AlertNo,
Starttimepatrol,
DATEADD(HOUR, 12, Starttimepatrol)
FROM tblAllPatrols
WHERE PatrolNo = 1
SELECT AlertNo,
(
SELECT COUNT(*)
FROM [tblAllPatrols] a
INNER JOIN #t1 b ON b.AlertNo = a.AlertNo
WHERE a.Starttimepatrol BETWEEN b.Starttime AND b.Endtime
) AS patrols
FROM [vwAlleDatensaetze]
GROUP BY AlertNo
I know that this is not the end of the Story, but as I cannot even count the numbers of patrols I cannot find a way to solve the Problem.
It should somehow "group" the patrols over 12-hour ranges per alert number and then count how many groups exists under the same alert number.
Hope, someone of you can lead me to the result I Need.
Thanks your help
Michael
Try this, it assumes that after the first patrol the billing period is a multiple of 8 hours from this time:
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
DECLARE #Patrols TABLE
(
AlertNo INT IDENTITY PRIMARY KEY,
StartTime DateTime
)
INSERT INTO #Patrols (StartTime)
VALUES ('20160126 09:57'),
('20160126 10:21'),
('20160126 19:54'),
('20160126 23:21'),
('20160127 08:13'),
('20160127 16:43'),
('20160128 07:33')
;WITH FirstBillingPeriodCTE
AS
(
SELECT MIN(StartTime) as BillingStartTime,
DateAdd(HOUR, 12, MIN(StartTime)) As BillingEndTime,
1 As BillingPeriod
FROM #Patrols
),
Numbers
As
(
SELECT num
FROM (Values (0),(1), (2), (3), (4), (5), (6), (7), (8), (9)) AS n(Num)
),
BillingPeriodsCTE
AS
(
SELECT DATEADD(Hour, 8 * (BillingPeriod + Numbers.Num), BillingStartTime) AS BillingStartTime,
DATEADD(Hour, 8 * (BillingPeriod + Numbers.Num), BillingEndTime) AS BillingEndTime,
BillingPeriod + Numbers.Num As BillingPeriod
FROM FirstBillingPeriodCTE
CROSS JOIN Numbers
)
SELECT COUNT(DISTINCT BillingPeriod)
FROM #Patrols P
INNER JOIN BillingPeriodsCTE B
ON P.StartTime >= B.BillingStartTime AND P.StartTime < B.BillingEndTime
Results:
| |
|---|
| 4 |
Here is a query that will give each billing period, up to 65,535 billing periods, accurate to the second.
My solution uses a calculated "Tally" table, but you would be better off in the long run to create your own physical "Tally" table in your database. See What is the best way to create and populate a numbers table? for more details.
You should be able to replace #tblPatrols with your patrol table.
DECLARE #tblPatrols TABLE (alertNo int, startTime datetime);
DECLARE #hoursPerBillingPeriod int, #toHoursConversion float;
SET #hoursPerBillingPeriod = 12;
SET #toHoursConversion = 60 * 60;
INSERT INTO #tblPatrols (alertNo, startTime)
VALUES
(1, '2016-01-28 05:57')
, (1, '2016-01-28 07:23')
, (1, '2016-01-28 08:10')
, (2, '2016-01-28 09:05')
, (2, '2016-01-28 12:22')
, (2, '2016-01-28 16:06')
, (2, '2016-01-28 23:45')
, (2, '2016-01-29 00:05')
, (3, '2016-01-28 12:00')
, (3, '2016-01-28 16:06')
, (3, '2016-01-29 00:00')
, (4, '2016-01-28 12:00')
, (4, '2016-01-28 16:06')
, (4, '2016-01-28 23:59:59.997')
;
;WITH
--......................
--This section used to simulate a "Tally" table... you would be better off to Create a physical Tally table
-- see: https://stackoverflow.com/questions/1393951/what-is-the-best-way-to-create-and-populate-a-numbers-table
Pass0 as (select 1 as C union all select 1) --2 rows
, Pass1 as (select 1 as C from Pass0 as A, Pass0 as B) --4 rows
, Pass2 as (select 1 as C from Pass1 as A, Pass1 as B) --16 rows
, Pass3 as (select 1 as C from Pass2 as A, Pass2 as B) --256 rows
, Pass4 as (select 1 as C from Pass3 as A, Pass3 as B)--65536 rows
, Tally as (select row_number() over(order by C) - 1 as N from Pass4) --65536 rows
--........................
,cteNumBillings as (
SELECT fp.alertNo
, firstPatrolTime = min(fp.startTime)
, lastPatrolTime = max(fp.startTime)
, hoursBetweenStartMinMax = datediff(second, min(fp.startTime), max(fp.startTime)) / #toHoursConversion
, numberOfBillingPeriods = floor(((datediff(second, min(fp.startTime), max(fp.startTime)) / #toHoursConversion) / #hoursPerBillingPeriod) + 1)
FROM #tblPatrols fp
GROUP BY fp.alertNo
)
SELECT b.alertNo
--This is the "x" value of the expression "Billing Period x of y"
, BillingPeriodNumber = t.N + 1
, BillingPeriodPatrolCount =
(select count(*)
from #tblPatrols p
where p.alertNo = b.alertNo
and p.startTime >= dateadd(hour, 12 * t.N, b.firstPatrolTime)
and p.startTime < dateadd(hour, 12 * (t.N+1), b.firstPatrolTime)
)
, BillingStart = dateadd(hour, 12 * t.N, b.firstPatrolTime)
, BillingEnd = dateadd(second, -1, dateadd(hour, 12 * (t.N + 1), b.firstPatrolTime))
--This is the "y" value of the expression "Billing Period x of y"
, TotalBillingPeriodCount = b.numberOfBillingPeriods
FROM cteNumBillings b
INNER JOIN Tally t ON t.N >= 0 and t.N < b.numberOfBillingPeriods
ORDER BY 1,2
;
I found a solution by myself, which seems to be easier and I could not find any mistake using it.
I take the first Startime of the first patrol in a variable. Then I use datediff for die difference of the all StartTimePatrol to the startime of the first patrol and divide it by 12 hours
set #BillingPeriod=(select (datediff(hour,#StartTime,#StartTimePatrol)/12)+1)
then I put the result of each record in a temp table
insert into #t2 ( Alertno, Starttime, Billings )
values ( #Alertno, #StartTimePatrol, #BillingPeriod )
then I group the altertno and Billings and count them
select alertno, count(Billings ) from (select alertno, Billings from #t2
group by alertno, Billings ) temp group by alertno
The result looks correct for me.
Thanks for all replies.
Michael
I have a database that stores data from the stock market.
There is a table with 3 columns: stockId, date, and volume
New data will be inserted into the table every trading day.
How can I get a result like 'Average volume for each stock over the last 10 trading days'?
SELECT AVG(volume) FROM mytable WHERE date >= (CURDATE() - INTERVAL 10 DAY)
EDIT:
Last 10 day groups, and their averages.
SELECT AVG(volume) FROM mytable GROUP BY date ORDER BY date DESC LIMIT 10
http://sqlfiddle.com/#!6/c8dbb/4
CREATE TABLE Stocks
([StockId] int, [Date] DateTime, [Volume] int)
;
INSERT INTO Stocks
([StockId], [Date], [Volume])
VALUES
(1, GetDate(), 1000),
(1, GetDate()+1, 2000),
(1, GetDate()+2, 4000),
(2, GetDate(), 1000),
(2, GetDate()+1, 1000),
(2, GetDate()+2, 500)
;
Select StockId, AVG(Volume) [AverageVolume]
FROM Stocks
WHERE [Date] >= DATEADD(dd, 0, DATEDIFF(dd, 0, GetDate())) - 10
Group by StockId
Order by StockId
SELECT SUM(volume)/10 FROM table_name
Where date Between Cast('7/18/13 12:01:01' As DateTime) And Cast('7/08/13 12:01:01' as DateTime)
I'm basing this off of Dodecapus answer and based off of comments you've given to other answers. I'm just including query in answer but check out sqlfiddle for working example with data.
http://sqlfiddle.com/#!6/91599/2
SELECT
StockId
,AVG(Volume) [AverageVolume]
FROM Stocks
WHERE [Date] IN
(
SELECT DISTINCT TOP 10 [Date] FROM Stocks ORDER BY [Date] DESC
)
GROUP BY StockId
ORDER BY StockId
This will only work if there is a record of at least one stock with volume per trading day.
Fun little query to write. Here it is:
SELECT AVG(x.Volume) FROM (SELECT Volume FROM StockTable WHERE Date BETWEEN
DATE_ADD(NOW(), INTERVAL -10 DAY) AND NOW())x
This is what I used to build a sample table to work off of in SQLFiddle:
CREATE TABLE StockTable (ID INT PRIMARY KEY AUTO_INCREMENT NOT NULL, Date DATETIME, Volume INT);
INSERT INTO StockTable (Date, Volume) VALUES (DATE_ADD(NOW(), INTERVAL 12 DAY), 1000), (DATE_ADD(NOW(), INTERVAL 1 DAY), 5000),
(DATE_ADD(NOW(), INTERVAL 0 DAY), 3000), (DATE_ADD(NOW(), INTERVAL -11 DAY), 6000), (DATE_ADD(NOW(), INTERVAL -5 DAY), 4000), (DATE_ADD(NOW(), INTERVAL 7 DAY), 9000);
Here is a link to the SQLFiddle of the query in action.
Idea behind the query: I create a derived table x which contains just the volumes within the past 10 days. Then I calculate the average of the volumes contained in that table. VoilĂ !
EDIT:
I realized specifically what you are looking for after reading through the other answers and comments. You are looking to get the average for each stock in the stock market over the last 10 days.
I built the sample table off of this:
CREATE TABLE StockTable (StockId INT NOT NULL, Date DATETIME, Volume INT);
INSERT INTO StockTable (StockId, Date, Volume) VALUES (1, DATE_ADD(NOW(), INTERVAL 6
DAY), 1000), (2, DATE_ADD(NOW(), INTERVAL 1 DAY), 5000),
(2, DATE_ADD(NOW(), INTERVAL 0 DAY), 3000), (3, DATE_ADD(NOW(), INTERVAL -8 DAY),
6000), (1, DATE_ADD(NOW(), INTERVAL -5 DAY), 4000),
(2, DATE_ADD(NOW(), INTERVAL 7 DAY), 9000);
And the query to get your results are:
SELECT StockId, AVG(Volume) FROM StockTable WHERE Date BETWEEN DATE_ADD(NOW(),
INTERVAL -10 DAY) AND NOW() GROUP BY StockId
Here is a link to the SQLFiddle of the query in action.