1

I am trying to do rather complex SQL query to produce a report. This is a database used by an inventory and accounting system.

Essentially I need to produce a report with the following columns

  • Month / Year (group results by month / year)
  • Reseller (order results by reseller with in the month / year group)
  • Total sales - Sales - Hardware
  • Total sales - Sales - Consumables

The following tables will need to be used in the report:

  • Invoice
  • Reseller
  • Job
  • JobStockItem
  • Stock

Essentially the query would need to start as:
1. Select all invoices from Invoice
2. Get the reseller name from Reseller.Name (join on Reseller.ID with Invoice.CustomerID)
3. Get the associated job ID from Job table (join on Job.InvoiceID with Invoice.ID)
4. Get each component of the invoice from JobStockItems (join JobStockItem.JobID on Job.ID)
5. Get the stock item in in the job from Stock (join on JobStockItems.StockId on Stock.ID) and see if the category (Stock.Category1) is either Hardware or Consumables
6. If the stock item is hardware or consumables, use the sale price in the JobStockItem (JobStockItem.PriceExTax) and add it towards the total for the month of the resellers purchases

The month and year come from the invoice date (Invoice.InvoiceDate).

Now I could produce this result myself by executing a bunch of queries and processing myself, one each for the above steps, but it's going to end up slow and I'm sure there'd have to be a query out there that could wrap all those requirements up and do it in one?

I have not attempted to do the query yet as to be honest, I don't know where to start - it's a lot more complex than anything I've done in the past.

I am just using Management Studio, not using Reporting Services, Crystal Reports or anything. My aim is to dump the output to HTML when I have it working.

Thanks heaps in advance.

4
  • I don't see where you'd get the month/year info from - you don't seem to be joining any "Sales" table or anything like that....
    – marc_s
    Jun 14, 2011 at 4:41
  • What tool are you using to generate the report? Crystal Reports, Microsoft Access, SQL Reporting... etc.
    – RThomas
    Jun 14, 2011 at 4:42
  • What's your attempt so far? Have you tried to have a go?
    – Bohemian
    Jun 14, 2011 at 4:42
  • Have addressed your comments in an edit update: In short, just using SQL Server Management Studio, date comes from Invoice.InvoiceDate and have not attempted yet - don't know where to start.
    – Sam
    Jun 14, 2011 at 4:46

3 Answers 3

4

It think if you Left Join into the JobStockItems table twice (once for hardware, and once for consumables), you can manage all that in one query. The final query will look something like this (Don't have my editor up right now, so apologies for any typos)

SELECT DATEPART(m, Invoice.InvoiceDate) month, 
       DATEPART(yy, Invoice.InvoiceDate) year, 
       Reseller.Name, 
       SUM(jobstockitems_hardware.Price) sales_hardware,
       SUM(jobstockitems_consumables.Price) sales_consumables, 
FROM Invoice
INNER JOIN Reseller
ON Invoice.CustomerID = Reseller.ID
INNER JOIN Job
ON Invoice.ID = Job.InvoiceID
LEFT JOIN (SELECT JobID, SUM(PriceExTax) Price 
           FROM JobStockItems 
           INNER JOIN Stock 
           ON JobStockItems.StockID = Stock.StockID
           AND Stock.Category1 = 'Hardware'
           GROUP BY JobID) jobstockitems_hardware
ON Job.ID = jobstockitems_hardware.JobID
LEFT JOIN (SELECT JobID, SUM(PriceExTax) Price 
           FROM JobStockItems 
           INNER JOIN Stock 
           ON JobStockItems.StockID = Stock.StockID
           AND Stock.Category1 = 'Consumables'
           GROUP BY JobID) jobstockitems_consumables
ON Job.ID = jobstockitems_consumables.JobID
GROUP BY DATEPART(m, Invoice.Date), 
         DATEPART(yy, Invoice.Date), 
         Reseller.Name
ORDER BY DATEPART(yy, Invoice.Date) ASC, 
         DATEPART(m, Invoice.Date) ASC, 
         Reseller.Name ASC

I'm assuming that Retailer has a column called Name that you want to return as well, feel free to change that to ID or whatever else you'd rather return.

Edit: Fixed query to remove duplicates

3
  • You will need to sum the Hardware and the Consumables tables in a subquery (or a sum with a condition - SUM(CASE WHEN Category1=?...)), otherwise the results will be off (PriceExTax will be duplicated for both categories) if there are multiple stock_consumables rows for a reseller. Jun 14, 2011 at 4:55
  • You're exactly right. I've edited the query to reflect that. Jun 14, 2011 at 5:05
  • Wow, kudos - works brilliantly. Sorry for my late reply, been incomunicado. Cheers @dp...
    – Sam
    Jun 15, 2011 at 8:22
0

Partly you want to PIVOT your results. So you can simply join your data together and let the PIVOT do the selecting and summarizing of categories:

select  *
from    (
        select  Year = datepart(year, i.InvoiceDate),
                Month = datepart(month, i.InvoiceDate),
                ResellerName = r.name,
                StockCategory = s.Category1,
                jsi.PriceExTax
        from    Invoice i
        inner join Reseller r
            on  r.ID = i.CustomerID
        inner join Job j
            on  j.InvoiceID = i.ID
        inner join JobStockItem jsi
            on  jsi.JobID = j.ID
        inner join Stock s
            on  s.ID = jsi.StockID
        ) d
pivot   (sum(PriceExTax) for StockCategory in (Hardware, Consumables)) p
order by Year, Month, ResellerName;

In the end you'll need some conditions in the inner query (e.g. where i.InvoiceDate between ...). Perhaps you have to multiply the PriceExTax with the amount in JobStockItem...

0

DPMattingley has produced a good query, but with one limitation - if a time period has no results, it won't show a row at all. This may well be an unlikely case in the specific example here but where it does happen it's annoying to find the report hides the zero results month!

My standard solution to this involves taking the month from a numbers table, which forces all time periods to appear. Using DPMattingley's query as a starting point -

select
    mths.month,
    mths.year,
    d.Name, 
    d.sales_hardware,
    d.sales_consumables
from
    /*All the in-range months on which to report*/
    (select
        datepart(m,dateadd(m,number,minDate)) month,
        datepart(yy,dateadd(m,number,minDate)) year
    from
        numbers n
            inner join (select min(invoice.invoicedate) as minDate from invoice) m
                on n.number between 0 and datediff(m,minDate,getdate())) mths 

        left join 
            /*Data for each month*/
            (SELECT DATEPART(m, Invoice.InvoiceDate) month, 
                    DATEPART(yy, Invoice.InvoiceDate) year, 
                    Reseller.Name, 
                    SUM(jobstockitems_hardware.Price) sales_hardware,
                    SUM(jobstockitems_consumables.Price) sales_consumables
            FROM 
                Invoice
                    INNER JOIN Reseller
                        ON Invoice.CustomerID = Reseller.ID
                    INNER JOIN Job
                        ON Invoice.ID = Job.InvoiceID
                    LEFT JOIN (SELECT JobID, SUM(PriceExTax) Price 
                               FROM JobStockItems 
                               INNER JOIN Stock 
                               ON JobStockItems.StockID = Stock.StockID
                               AND Stock.Category1 = 'Hardware'
                               GROUP BY JobID) jobstockitems_hardware
                        ON Job.ID = jobstockitems_hardware.JobID
                    LEFT JOIN (SELECT JobID, SUM(PriceExTax) Price 
                               FROM JobStockItems 
                               INNER JOIN Stock 
                               ON JobStockItems.StockID = Stock.StockID
                               AND Stock.Category1 = 'Consumables'
                               GROUP BY JobID) jobstockitems_consumables
                        ON Job.ID = jobstockitems_consumables.JobID
            GROUP BY    DATEPART(m, Invoice.Date), 
                        DATEPART(yy, Invoice.Date), 
                        Reseller.Name) d
                on mths.month=d.month
                and mths.year=d.year

ORDER BY    mths.month ASC, 
            mths.year ASC, 
            Reseller.Name ASC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.