473,699 Members | 2,254 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Graph of top four products each month for last 6 months?

Microblitz
40 New Member
Graph of top four products each month for last 6 months?
(Yeah I know I typ'od the title)

I need create a chart which displays the four highest selling products for each month in the last 6 months to be displayed in a report.

Ive managed to get all the products for each month for the last six months but im unsure how to filter so it displays only the top four for each month.

Ive done some programming but I thiinnk im going about this wrongly.

This is my code so far

Expand|Select|Wrap|Line Numbers
  1. DECLARE @StartDate        SMALLDATETIME -- Variables for the dashboard
  2. DECLARE @EndDate        SMALLDATETIME
  3.  
  4. SET @StartDate            = DATEADD(s,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0)) -- get todays month minus 6
  5. SET @EndDate            = GETDATE() -- get todays date
  6.  
  7. ----
  8.  
  9. DECLARE @WhereDateStart        SMALLDATETIME
  10. DECLARE @WhereDateEnd        SMALLDATETIME
  11.  
  12. SET @WhereDateStart = CONVERT(SMALLDATETIME,'01/' + LTRIM(STR(MONTH(@StartDate))) + '/' + LTRIM(STR(YEAR(@StartDate))))
  13.  
  14. SET @WhereDateEnd = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate)+1,0))-1
  15. -- we want each date/month minus six months for filter
  16.  
  17.      SELECT -- Set up columns and graph output.
  18.  
  19.         LEFT(Products.ProductId,14) AS ChartLabel,
  20.         Products.ProductId,
  21.         CONVERT(INT, SUM(ManufacturingOrders.QuantityMade)) AS QuantityMade 
  22.         ,
  23.         CONVERT(CHAR(10), 
  24.             LTRIM(STR(YEAR(ManufacturingOrders.ReleaseDate))) + '/' + 
  25.             LTRIM(STR(MONTH(ManufacturingOrders.ReleaseDate)))) AS ReleaseDate -- trim dates
  26.     FROM
  27.         ManufacturingOrders
  28.         INNER JOIN Products ON ManufacturingOrders.Product = Products.Product -- Get the product type
  29.         INNER JOIN Classifications ON Products.Classification = Classifications.Classification -- Get the Product number
  30.     WHERE
  31.  
  32.          Products.ProductId IN (
  33.  
  34.             SELECT  Products.ProductId
  35.  -- sales code
  36.             FROM       Products INNER JOIN Classifications ON Products.Classification = Classifications.Classification
  37.  
  38.             WHERE    Classifications.ClassificationId = 'BOOK'
  39.                                                                       )     
  40.  
  41.                                   AND    ManufacturingOrders.ReleaseDate BETWEEN @WhereDateStart AND @WhereDateEnd
  42.           AND       ManufacturingOrders.SystemType = 'B'
  43.                                   AND       QuantityMade > 0
  44.  
  45.     GROUP BY
  46.  
  47.         Products.ProductId
  48.         ,
  49.         YEAR(ManufacturingOrders.ReleaseDate)
  50.         ,
  51.         MONTH(ManufacturingOrders.ReleaseDate)
  52.     ORDER BY
  53.         ReleaseDate
  54.          ,
  55.          ProductId
  56.  
This produces ChartLabel,Prod uctId,QunatityM ade,ReleaseDate columns.

but its everything for each month, I just want the top 4 for each month to be sent to the graph.
Aug 13 '10 #1
12 2979
ck9663
2,878 Recognized Expert Specialist
Sorry, too lazy to read your code so I'll post something similar :)

Try doing something like this:

Expand|Select|Wrap|Line Numbers
  1. select * from 
  2. (
  3. select
  4. rank = row_number() over (partition by month order by numberofsolditems desc)
  5. month, numberofsolditems
  6. from 
  7. (your subquery) q) z
  8. where rank <= 4
  9.  
Happy Coding!!!

~~ CK
Aug 13 '10 #2
Microblitz
40 New Member
Care to elaborate?
Aug 25 '10 #3
NeoPa
32,569 Recognized Expert Moderator MVP
What do you need help with?

Have you tried looking through it to see how you can apply these techniques to your situation?
Aug 25 '10 #4
Microblitz
40 New Member
Well I got this far last night but it doesnt work.

It produces a "Msg 8120, Level 16, State 1, Line 14
Column 'Products.Produ ctId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
"

WHich is being caused by the inclusion of the SELECT product.product sId

But the function being proposed is one which I don't fully understand.

Specifically these dot functions such as the ".ss" I can only assume is to identify specific variables. I've never seen them before in any of the code I've researched (Remember I'm only about 16 hours into programming this language).

I have a database which contains information about stock across multiple tables and the point is to locate the top 4 best selling items on a per month basis over the last 6 months then plot them on a barograph. So what I am trying to do is even more complex for me than I am showing here. I can handle the graphics part I just need to figureout how to do what in any normal programming language would be a nested loop.


Expand|Select|Wrap|Line Numbers
  1. DECLARE @StartDate        SMALLDATETIME
  2. DECLARE @EndDate        SMALLDATETIME
  3.  
  4. SET @StartDate            = DATEADD(s,0,DATEADD(mm, DATEDIFF(m,0,GETDATE())-6,0))
  5. SET @EndDate            = GETDATE()
  6.  
  7.  
  8. DECLARE @WhereDateStart        SMALLDATETIME
  9. DECLARE @WhereDateEnd        SMALLDATETIME
  10.  
  11. SET @WhereDateStart = CONVERT(SMALLDATETIME,'01/' + LTRIM(STR(MONTH(@StartDate))) + '/' + LTRIM(STR(YEAR(@StartDate))))
  12. SET @WhereDateEnd = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@EndDate)+1,0))-1
  13.  
  14. SELECT * FROM
  15.         (
  16.                 SELECT 
  17.                     Products.ProductId,
  18.                     CONVERT(INT, SUM(ManufacturingOrders.QuantityMade)) AS Quantity,
  19.                     CONVERT(CHAR(10), 
  20.                                 LTRIM(STR(YEAR(ManufacturingOrders.ReleaseDate))) + '/' + 
  21.                                 LTRIM(STR(MONTH(ManufacturingOrders.ReleaseDate)))) AS ReleaseDate,
  22.  
  23.                     ROW_NUMBER()OVER (ORDER BY  ReleaseDate,Quantity DESC)AS RowNumber,
  24.                     RANK() OVER (ORDER BY ReleaseDate) AS Rank
  25.  
  26.                 FROM ManufacturingOrders
  27.  
  28.                     INNER JOIN Products ON ManufacturingOrders.Product = Products.Product
  29.                     INNER JOIN Classifications ON Products.Classification = Classifications.Classification
  30.  
  31.                 WHERE 
  32.  
  33.                     Classifications.ClassificationId = 'STOCK 332' 
  34.                     AND    ManufacturingOrders.ReleaseDate BETWEEN @WhereDateStart 
  35.                     AND @WhereDateEnd AND ManufacturingOrders.SystemType = 'C'
  36.  
  37.  
  38.         Group By ReleaseDate,Quantity)ss
  39.  
  40. WHERE ss.RowNumber = ss.Rank or ss.RowNumber = ss.Rank+1
  41.  
Aug 26 '10 #5
Microblitz
40 New Member
Conversely if I simplyfy it as much as possible and take CK9663's original code and simply insert what I think are the relevent fields producing this version;

Expand|Select|Wrap|Line Numbers
  1. SELECT * FROM  
  2. SELECT 
  3. Products.ProductId,
  4. CONVERT(INT, SUM(ManufacturingOrders.QuantityMade)) AS Quantity, -- calculate total sales
  5.  
  6. RANK = ROW_NUMBER() OVER (PARTITION BY MONTH ORDER BY Quantity DESC) 
  7. MONTH, Quantity
  8.  
  9. FROM ManufacturingOrders
  10.  
  11. INNER JOIN Products ON ManufacturingOrders.Product = Products.Product
  12. INNER JOIN Classifications ON Products.Classification = Classifications.Classification
  13.  
  14. (
  15. Classifications.ClassificationId = 'stock item 443' 
  16. AND    ManufacturingOrders.ReleaseDate BETWEEN @WhereDateStart 
  17. AND @WhereDateEnd AND ManufacturingOrders.SystemType = 'C') q) z 
  18. WHERE RANK <= 4 
  19.  
It produces;
"Msg 102, Level 15, State 1, Line 7
Incorrect syntax near 'MONTH'."


since the only thing I changed in that line of code was the quantity variable, I'm somwhat puzzled as to why there is a syntax error. All of the commands in that line (Except "Quantity") are reserved words.
Aug 26 '10 #6
NeoPa
32,569 Recognized Expert Moderator MVP
Let's take a bunch of steps backwards. I do not even see how your attempts match the suggestion, but as you say you're new to this.

A step at a time then, do you understand subqueries (Subqueries in SQL) in SQL?
There are two levels of subquery in the proposed solution but, although there is a sort of one in one of your examples, it doesn't appear you have what is suggested in the original.
Aug 26 '10 #7
Microblitz
40 New Member
Well I do now, though my guess work was reasonably accurate. It provides a seconed layer of filtering to the original query.
I guess the two levels of sub query is the (sub query here) and the final line in the original example.
"where rank <= 4 "
Aug 26 '10 #8
NeoPa
32,569 Recognized Expert Moderator MVP
ck9663:
Expand|Select|Wrap|Line Numbers
  1. select * from 
  2. (
  3. select
  4. rank = row_number() over (partition by month order by numberofsolditems desc)
  5. month, numberofsolditems
  6. from 
  7. (your subquery) q) z
  8. where rank <= 4
Pretty well yes. Let me explain :
In line #7 (your subquery) q specifies your query and the result set is renamed (ALIASed) to [q]. This is equivalent to (your subquery) AS q.

From there the next level query (named [z] now) would be lines #2 through #7.
Expand|Select|Wrap|Line Numbers
  1. (
  2. SELECT [Rank] = ROW_NUMBER() OVER (PARTITION BY [Month] ORDER BY [NumberOfSoldItems] DESC)
  3.        [Month]
  4.      , [NumberOfSoldItems]
  5. FROM   (your subquery) AS q) AS z
I think possibly an extra comma (,) may be required before [Month].

This implies that your query must provide data for [Month] and [NumberOfSoldIte ms].

Anyway, if we now call this [QueryZ] then we are left with :
Expand|Select|Wrap|Line Numbers
  1. SELECT *
  2. FROM   (QueryZ) AS [z]
  3. WHERE  [Rank] <= 4
Does that all start to make a little more sense?
Aug 26 '10 #9
Microblitz
40 New Member
Yes that makes a lot more sense as soon as you mentioned the "AS" keyword.

The "z" routeine I can leave as is, but the 'q' query needs to specify the particulatr brand of product from a related search.

This is the relationship that needs to be parsed
Expand|Select|Wrap|Line Numbers
  1. FROM ManufacturingOrders 
  2.  
  3. INNER JOIN Products ON ManufacturingOrders.Product = Products.Product 
  4. INNER JOIN Classifications ON Products.Classification = Classifications.Classification 
Which goes inside the query q brackets?
and continues with ;
Expand|Select|Wrap|Line Numbers
  1. Classifications.ClassificationId = 'stock item 443'  
  2. AND    ManufacturingOrders.ReleaseDate BETWEEN @WhereDateStart  
  3. AND @WhereDateEnd AND ManufacturingOrders.SystemType = 'C'
?

I'm not stupid but the syntax of this language is freakish in comparision with those that I have played with in the past. I guess it doesnt help to only have been supplied with one book which is Sams teach yourself Microsoft SQL Server T-SQL.

Any suggestions for a quick rummage in amazon.co.uk for a better book than this. It is ... well erm.. brief.. :)
Aug 27 '10 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

16
41629
by: sandy | last post by:
Hi, Using Java script I am trying to create code where when you place in the start date it automatically calculates 6 months for the experations date. For example when I place 01/01/04 as the issue date the experation date should automaically generate as 06/01/04. I would appreciate it if anyone could help me. Thank you Sandy
1
5194
by: Finlay | last post by:
Hi Group I am designing a report that should show a meter reading for each month and the previous meter reading for the previous month. The months are text stored in a field tMonth. The current month is easy to pull out of the data base but I don't know how to get the previous months meter reading. The previous reading is subtracted from the current reading to get the
9
1868
by: Robin Tucker | last post by:
Hiya, I need to test "relative dates" in my program, such as "last six months" or "last 3 months" or "in the last week" etc. How can I do this with a DateTime structure? ie. If NodeDate >= CurrentDate - six months (etc.)
3
10800
by: remya1000 | last post by:
i'm using ASP with MSAccess as database. i have two buttons and two textbox in my page. when i press my first button (First month) i need to display the current month in one textbox and last one months date in another textbox. and while pressing the second button (submit) i need to display the date displayed in the textbox as itself and the records between thoses two dates. if that date is still there in the textbox only i can sort the...
2
1579
by: nsymiakakis | last post by:
Hello Everyone, I am almost completed with this database, the only thing left is to graph the results of a query. I built a parameter query that gives me totals for a date range that I enter. This works great. I created a column called "Month", and I am entering the month and year corresponding to the "Date" field. ie. (03/15/06 for the date) (Mar-06) for Month. If I do the Query to show me 1/1/2006 to 12/31/2006, I get the results with Date...
3
4866
by: Johan Mcgillicutty | last post by:
Could use some help on this one- I’m new to MS Access, and even newer to SQL. I’m building a database for clients of a treatment center, and need to keep track of when people are due for their annual physical. As near as I can tell, the simplest way to do this is to simply record when the physical was, and build a query to compile a list of all the entries from the current month, one year ago. This would enable a report to be created with...
5
1644
by: rekhasc | last post by:
hi all............... in my proj i am using a mschart .... now what i want is i want to display the graph amount v/s months I did the graph which shows date v/s amount its working good... i used the sql query for that.... for month also i wrotequery but its not working properly.... what i need is it should add all the amounts which are entered in the particular dates on that month then it show the graph... plz if u know that send me...
11
2459
by: Harlin Seritt | last post by:
Is there a module that can pull str values for say the last 3 months? Something like: print lastMonths(3) Thanks
3
1659
by: Supermansteel | last post by:
I have a Query/Report that I am running a Date Parameter so it only pulls in the information for the End of Month Results for that person. It runs the Avg for everyone for that month also. I was trying to figure out a way to pull in there results from the following month. I found DateSerial(Year(Date),Month(Date)-1,1) that pulled in last month, but how do I pull in Last month Production, calls/hour etc on how the individual did. Is there a way...
9
1327
by: mikewin86 | last post by:
Hello , I would like to ask a question concerned with SQL Server 2000 query. I've got a table PurchaseDetails and I would like to query from it. I want all product records with last purchase ID. The following is my query statements. SELECT MAX(PurchaseID) AS LastID, ProductID, BatchNo FROM PurchaseDetails GROUP BY ProductID, BatchNo When I run this query statements , I got all products and all records (i.e. not only last...
0
9032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8880
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7745
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5869
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4374
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4626
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2344
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.