Log in  ::  Register  ::  Not logged in

## Current Order Date and Average Count of Orders for Three Prior Days

 Author Message David-250683 SSCrazy Group: General Forum Members Points: 2276 Visits: 476 Want to get 1) the OrderDate and 2) the daily average of total Orders for that day and two previous days where there are orders.As an example, I use the Shipping.Orders Table from the Northwind database from SQL Server 2005.USE NorthwindGOSELECT OrderDate, COUNT(OrderDate) FROM Shipping.OrdersWHERE OrderDate Between '04-30-1998' AND '05-06-1998'GROUP BY OrderDateORDER BY 1 DESCWith this basic query you can see there are 4 orders on 5/6, 4 orders on 5/5 and 3 orders on 5/4.Total orders for the three day period is 11. Average of 3.67.Total orders for the next three day period starting from the next OrderDate is 10. Average of 3.33So I would want the output to look likeOrderDate AverageOrderCount5/6 3.675/5 3.33and so on...SELECT COUNT(OrderDate)FROM Shipping.OrdersWHERE OrderDate Between '04-30-1998' AND '05-06-1998'ORDER BY 1 DESC Sergiy SSC Guru Group: General Forum Members Points: 72316 Visits: 13338 Total number of orders for the next 3 days is 7: 4 + 3 + 0.Can you explain your logic more precisely? David-250683 SSCrazy Group: General Forum Members Points: 2276 Visits: 476 I can try. Can you explain what "ext" means precisely? Sergiy SSC Guru Group: General Forum Members Points: 72316 Visits: 13338 I fixed the typo. David-250683 SSCrazy Group: General Forum Members Points: 2276 Visits: 476 Here's one solution but it is quite lengthy. I'm sure there is a more efficient answer. So please show me your wisdom!I used a different column though - RequiredDate instead of OrderDate.Here's the query to check the result set against. And below that - my inefficient, but working solution.--Check TableUSE NorthwindGOSELECT RequiredDate, COUNT(RequiredDate) FROM Shipping.OrdersWHERE RequiredDate Between '1998-05-01' AND '1998-06-11'GROUP BY RequiredDateORDER BY 1 DESC------- Inefficient Solution --------DECLARE @counter int, @counter2 int, @date smalldatetime, @scope intSELECT @counter = 1, @counter2 = 1DECLARE @Time TABLE ( ID int IDENTITY (1,1), timex smalldatetime )--Gather dates to report on-- Note: not all dates have a RequiredDateINSERT @Time(timex)SELECT DISTINCT RequiredDateFROM Shipping.OrdersWHERE RequiredDate BETWEEN '1998-05-01' AND '1998-06-11'ORDER BY 1 DESC-- Select 1st DateSELECT @date = (SELECT timex FROM @Time WHERE ID = 1)-- Create Results tableDECLARE @Results TABLE ( t_RequiredDate smalldatetime, t_count int )SELECT @scope = SCOPE_IDENTITY()-- Set @scope to number of RequiredDates in @TimeWHILE @counter < @scopeBEGININSERT @ResultsSELECT timex,(SELECT COUNT(RequiredDate) FROM Shipping.Orders WHERE RequiredDate IN (SELECT distinct TOP 3 RequiredDate -- Only want count of last three RequiredDates FROM Shipping.Orders WHERE RequiredDate BETWEEN DATEADD(day, -10, @date) AND @date order by 1 desc) --Goes back 10 because not all dates have values ) FROM @Time WHERE ID = @counter2SELECT @counter2 = @counter2 + 1SELECT @date = (SELECT timex FROM @Time WHERE ID = @counter2)SELECT @counter = @counter + 1END-- Retrieve ResultsSELECT t_RequiredDate, LTRIM(STR(CAST(t_count as float)/ 3, 4,2)) --obtain averageFROM @Results ORDER BY 1 DESC Sergiy SSC Guru Group: General Forum Members Points: 72316 Visits: 13338 Still it's not clear what are trying to achieve.As for me the solution you posted is logically wrong.But I cannot be sure because I don't have an idea what's the task you need to solve. David-250683 SSCrazy Group: General Forum Members Points: 2276 Visits: 476 Here's a shorter version, but I know there is still room for improvement.DECLARE @date smalldatetime, @counter intSELECT @date = '1998-06-11', @counter = 1DECLARE @Results TABLE ( t_RequiredDate smalldatetime, t_count int )-- Select @counter to desired result set sizeWHILE @counter < 10BEGIN WHILE (SELECT DISTINCT RequiredDate FROM Shipping.Orders WHERE RequiredDate = @date) IS NULL BEGIN SELECT @date = DATEADD(day, -1, @date) END INSERT @Results SELECT RequiredDate, (SELECT COUNT(RequiredDate) FROM Shipping.Orders WHERE RequiredDate IN (SELECT distinct TOP 3 RequiredDate -- Only want count of last three RequiredDates FROM Shipping.Orders WHERE RequiredDate BETWEEN DATEADD(day, -10, @date) AND @date order by 1 desc) --Goes back 10 because not all dates have values) FROM Shipping.Orders WHERE RequiredDate = @date SELECT @date = DATEADD(day, -1, @date) SELECT @counter = @counter + 1ENDSELECT DISTINCT t_RequiredDate, LTRIM(STR(CAST(t_count as float)/ 3, 4,2)) --obtain averageFROM @Results ORDER BY 1 DESC Sergiy SSC Guru Group: General Forum Members Points: 72316 Visits: 13338 David,that was not much help.You cannot build any right query unless you know what you are querying for.I still see the same logical error (according to my understanding) in the approach, but I cannot tell for sure if it's an error in fact.Can you tell IN PLAIN ENGLISH WHAT ARE YOU LOOKING FOR?What does it really mean: the day and 2 earlier days?Which days to be taken as "earlier days"? Greg Snidow SSChampion Group: General Forum Members Points: 11105 Visits: 2508 It kind of seems to me David is looking for a rolling three day average. If today is the third day of the month, say 10/3, then he needs the average for 10/1+10/2+10/3. Tomorrow will be the fourth day of the month so he will need the average for 10/2+10/3+10/4, and so on. Greg_________________________________________________________________________________________________The glass is at one half capacity: nothing more, nothing less. Greg Snidow SSChampion Group: General Forum Members Points: 11105 Visits: 2508 David I do not have the sample databases, so I improvised. I think this may be what you are looking to do? I am fairly sure this is *not* the way you want to do this because it creates a triangular join, but it works.--Create test table and populate with dataIF OBJECT_ID('tblOrders','u') IS NOT NULLDROP TABLE tblordersCREATE TABLE tblOrders(ID INT IDENTITY(1,1),ORDER_DT SMALLDATETIME,)INSERT INTO tblOrders (ORDER_DT)SELECT '10/5/2007' UNION ALLSELECT '10/5/2007' UNION ALL SELECT '10/5/2007' UNION ALLSELECT '10/5/2007' UNION ALL SELECT '10/4/2007' UNION ALLSELECT '10/4/2007' UNION ALL SELECT '10/4/2007' UNION ALLSELECT '10/3/2007' UNION ALL SELECT '10/2/2007' UNION ALLSELECT '10/2/2007' UNION ALL SELECT '10/2/2007' UNION ALLSELECT '10/1/2007' UNION ALL SELECT '10/3/2007' UNION ALLSELECT '10/6/2007' UNION ALL SELECT '10/6/2007' UNION ALLSELECT '10/6/2007' UNION ALL SELECT '10/6/2007' UNION ALLSELECT '10/6/2007' UNION ALL SELECT '10/6/2007' UNION ALLSELECT '10/6/2007' UNION ALL SELECT '10/3/2007' UNION ALLSELECT '10/2/2007' UNION ALL SELECT '10/1/2007' UNION ALLSELECT '10/6/2007' --Create temp table to hold total # orders per dayIF OBJECT_ID('TempDB..#Temp','u') IS NOT NULLDROP TABLE #TempCREATE TABLE #Temp(ID INT IDENTITY(1,1),ORDER_DT SMALLDATETIME,DT_Total FLOAT,)--Populate temp tableINSERT INTO #TempSELECT ORDER_DT,DT_Total = COUNT(order_dt) FROM tblOrders GROUP BY order_dt ORDER BY order_dt DESC--Find 3 day averageSELECTt1.ORDER_DT,t1.DT_Total,( SELECT ROUND(SUM(t2.dt_total)/3,1) FROM #temp t2 WHERE t2.order_dt = t1.order_dt OR t2.order_dt = t1.order_dt - 1 OR t2.order_dt = t1.order_dt -2 ) AS Total FROM #Temp t1 Greg_________________________________________________________________________________________________The glass is at one half capacity: nothing more, nothing less.

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization      Security and Auditing SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      Question of the Day (QOD)      SQL Server Security Skills Microsoft Access      Microsoft Access Products and Books      Third Party Products         CA         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Golden Gate Software         Idera         Lumigent         Red Gate Software         Quest Software         ApexSQL         Sonasoft      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss Data Warehousing Books          Discuss T-SQL Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12

## Search

 Copyright © 2002-2018 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.