Question

I have a table Supplier with two columns, TotalStock and Date. I'm trying to write a single query that will give me stock totals by week / month / year for a list of suppliers.

So results will look like this..

SUPPLIER  WEEK MONTH YEAR
SupplierA 50   100   2000
SupplierB 60   150   2500
SupplierC 15   25    200

So far I've been playing around with multiple selects but I can't get any further than this:

SELECT Supplier,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-5-12'
    GROUP BY    Supplier
    ) AS StockThisWeek,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-5-1'
    GROUP BY    Supplier
    ) AS StockThisMonth,
    (
    SELECT      Sum(TotalStock)
    FROM        StockBreakdown
    WHERE       Date >= '2014-1-1'
    GROUP BY    Supplier
    ) AS StockThisYear

This query throws an error as each individual grouping returns multiple results. I feel that I'm close to the solution but can't work out where to go

Was it helpful?

Solution

You don't have to use subqueries to achieve what you want :

SELECT Supplier
     , SUM(CASE WHEN Date >= CAST('2014-05-12' as DATE) THEN TotalStock END) AS StockThisWeek
     , SUM(CASE WHEN Date >= CAST('2014-05-01' as DATE) THEN TotalStock END) AS StockThisMonth
     , SUM(CASE WHEN Date >= CAST('2014-01-01' as DATE) THEN TotalStock END) AS StockThisYear
FROM  StockBreakdown
GROUP BY Supplier

OTHER TIPS

You may need to make the selects for the columns return only a single result. You could try this (not tested currently):

SELECT Supplier,
(
    SELECT TOP 1 StockThisWeek FROM
    (
       SELECT      Supplier, Sum(TotalStock) AS StockThisWeek
       FROM        StockBreakdown
       WHERE       Date >= '2014-5-12'
       GROUP BY    Supplier
    ) tmp1
    WHERE tmp1.Supplier = Supplier 
) AS StockThisWeek,

(
    SELECT TOP 1 StockThisMonth FROM
    (
       SELECT      Supplier, Sum(TotalStock) AS StockThisMonth
       FROM        StockBreakdown
       WHERE       Date >= '2014-5-1'
       GROUP BY    Supplier
    ) tmp2
    WHERE tmp2.Supplier = Supplier 
) AS StockThisMonth, 

...

This selects the supplier and then tries to create two columns StockThisWeek and StockThisMonth by selecting the first entry from the select you created before. As through the GROUP BY there should only be one entry per supplier, so you don't lose and data.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top