Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Query for generating monthly sales report!!!!!!!!!!!!!!!!!

Posted on 2008-10-03
8
Medium Priority
?
3,624 Views
Last Modified: 2008-10-24
Hi Experts,

           I am working on a project where I need to generate a monthly sales report. In have two table one with customer information like Cust_id, Cust_name, etc. and other with invoice amount info like Cust_id, Sale_Date, Amount, etc. Now in the report I need to show Customer wise monthly sale report where user will give me input for how many months he wants report for suppose User inputs 6 then I need to show previous 6 months sales report. Now after extracting this report I need to display a column for each month in the report like for 6 months

Eg.

Name    Sep.    Aug     July    June     May     April
Sam     1000    100      -        900       -          -
John     500      235     764    -           43       -
Bill        3333    -           -        1129    8888   4312



I Hope I have explained the question in the best possible way I could have done. But if u need any clarification you can ask me.

I need a query for this


Can any one help me.

Its urgent.....


Thanx in advance..


Regards,
Param
0
Comment
Question by:Paramhans
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 37

Expert Comment

by:momi_sabag
ID: 22639809
this can be done rather easly in dynamic sql or a bit harder in static sql
are you allowed to use dynamic sql?
0
 
LVL 4

Accepted Solution

by:
petr_hlucin earned 400 total points
ID: 22639825
Hi Param,

Since you need a 2D table with values of the same kind (not an ordinary dataset which we can look at as a list of data items) you can't get the table described in your problem. In order to get this data in 1 query (which you probably want) you'll have to obtain a table which will look like this:

Cust_id  Name  m    y        sales
1            Sam    9    2007   1000
2            John    9    2007   500
...

So execute such select:

select c.Cust_id, c.Cust_Name, sum(Amount) sales, DATEPART(month, i.Sale_Date) m, DATEPART(year, i.Sale_Date) y
from ivoice i, cust c
where c.Cust_id = i.Cust_id and
i.Sale_Date < ... and i.Sale_Date > ...
group by Cust_id, m, y

Don't forget to replace ... with apropriate dates of begin and end of the report period.
0
 
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 1200 total points
ID: 22639849
The PIVOT will prove to be the most challenging part of this.  So to start out, let us at get the data in rows first to ensure it is what you need then try to figure out PIVOT as SQL 2005 offers a nice method; however, it requires hardcoded columns.  You could always take the result and utilize Excel/Access PIVOT table which will dynamically build columns or you can use dynamic SQL to create select statement with PIVOT keyword in SQL Server.

But anyway, here is the first part:
DECLARE @numMonths INT
SET @numMonths = 6
-- invoices represents your table of invoices
-- customers represents your table of customers
;WITH CustomerInvoices AS (
SELECT c.Cust_name AS [Name]
, Year(i.Sale_Date) AS [Yr] /* in case span multiple years */
, Month(i.Sale_Date) AS [Mnth]
, DateName(mm, i.Sale_Date) AS [MnthName]
, CAST(SUM(IsNull(i.Amount, 0.00)) AS Money) AS TotalAmount /* SUM() should eliminate NULLs, but for clarity */
FROM Customers c LEFT JOIN Invoices i
ON c.Cust_ID = i.Cust_ID
WHERE i.Sale_Date >= DATEADD(mm, - @numMonths, DATEDIFF(dd, 0, GETDATE() - DAY(GETDATE()) + 1))
AND i.Sale_Date < DATEADD(dd, - DAY(GETDATE()) + 1, DATEDIFF(dd, 0, GETDATE()))
GROUP BY c.Cust_Name, Year(i.Sale_Date), Month(i.Sale_Date), DateName(mm, i.Sale_Date)
) 
SELECT [Name], [MnthName], [TotalAmount]
FROM CustomerInvoices
ORDER BY YR DESC, MNTH DESC

Open in new window

0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 60

Expert Comment

by:Kevin Cross
ID: 22639851
Took me a little bit to type out my thought and now I see some other posts in here, so I apologize for duplication.
0
 
LVL 42

Assisted Solution

by:dqmq
dqmq earned 400 total points
ID: 22639863
You may want to refine how you select the date range, but the basic query looks like this:
TRANSFORM Sum(Sale.Amount) AS SumOfAmount
SELECT Cust.CustName
FROM Cust INNER JOIN Sale ON Cust.CustId = Sale.CustId
WHERE (((Sale.SaleDate) Between DateAdd("M",-1*[?NumberOfMonths],[?End Date]) And [?End Date]))
GROUP BY Cust.CustName
PIVOT MonthName(Month([SaleDate]),True) In ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

Open in new window

0
 
LVL 42

Expert Comment

by:dqmq
ID: 22639866
Darn...thought I was working the Access forum.  Disregard previous answer.  Too late at night...time for bed
0
 
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 1200 total points
ID: 22639878
The equivalent to this in MS SQL is the following (using column names from my above query for example):
PIVOT (SUM(TotalAmount) FOR MnthName IN ('January','February','March','April','May','June','July','August','September','October','November','December')) p

Open in new window

0
 
LVL 60

Assisted Solution

by:Kevin Cross
Kevin Cross earned 1200 total points
ID: 22639885
dgmg, you made me do a double take on the question and zone. :) definitely a little easier in Access to pivot.  Can even get the base data per a query like mine in rows and then use the crosstab wizard which will dynamically pick up columns names, etc.

I have never tried this, but do you know for the asker's sake if using linked servers in MS Access to the SQL database tables named like in your example Cust and Sale and then construct a query in access using your comment --- would that work?  Don't have Access on this machine to try.  I believe it would, but as I said haven't tried as usually dealing with imported data or using PIVOT view on SQL tables within Access.
0

Featured Post

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article will provide a solution for an error that might occur installing a new SQL 2005 64-bit cluster. This article will assume that you are fully prepared to complete the installation and describes the error as it occurred durin…
I've encountered valid database schemas that do not have a primary key.  For example, I use LogParser from Microsoft to push IIS logs into a SQL database table for processing and analysis.  However, occasionally due to user error or a scheduled task…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

670 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question