1

I have my database table ABC as shown below :

  ItemId  Month  Year    Sales
   1        1     2013    333
   1        2     2013    454
   2        1     2013     434

and so on .

I would like to write a query to find the top 3 items that have had the highest increase in sales from last month to this month , so that I see somethinglike this in the output. Output :

 ItemId    IncreaseInSales
  1               +121
  9                +33
  6                +16    

I came up to here :

select 

 (select Sum(Sales) from ABC where [MONTH] = 11  )
 -
 (select Sum(Sales) from ABC where [MONTH] = 10) 

I cannot use a group by as it is giving an error . Can anyone point me how I can proceed further ?

3
  • Where are the ItemID's 9 and 6 are coming from? Dec 6, 2013 at 20:18
  • ItemId's are in the Table ABC. I didnt put all the itemids in the question above . But there are a lot more entries to the table ABC in my original table
    – CodeNinja
    Dec 6, 2013 at 20:20
  • 3
    Why is this tagged with three different versions? If your query has to work across all three versions, usually it's best to just tag with the minimum version. Otherwise you may get answers using LAG/LEAD which are only valid in SQL Server 2012. Dec 6, 2013 at 20:28

7 Answers 7

1

Assuming that you want the increase for a given month, you can also do this with an aggregation query:

select top 3 a.ItemId,
       ((sum(case when year = @YEAR and month = @MONTH then 1.0*sales end) /
         sum(case when year = @YEAR and month = @MONTH - 1 or
                       year = @YEAR - 1 and @Month = 1 and month = 12
                  then sales end)
        ) - 1
       ) * 100 as pct_increase
from ABC a
group by a.ItemId
order by pct_increase desc;

You would put the year/month combination you care about in the variables @YEAR and @MONTH.

EDIT:

If you just want the increase, then do a difference:

select top 3 a.ItemId,
       (sum(case when year = @YEAR and month = @MONTH then 1.0*sales end) -
        sum(case when year = @YEAR and month = @MONTH - 1 or
                      year = @YEAR - 1 and @Month = 1 and month = 12
                 then sales
            end)
       ) as difference
from ABC a
group by a.ItemId
order by difference desc;
3
  • I don't understand why @Month and @Year are variables. I thought OP wants to know the three items with the greatest sales-difference from one month to the next. Dec 6, 2013 at 21:54
  • @TimSchmelter . . . The OP states "top 3 items that have had the highest increase in sales from last month to this month". To me, this makes it clear that s/he wants the most recent presumably complete months. Dec 6, 2013 at 21:55
  • The question is not that clear. I assume that "last to this month" means "last to next month", the desired output and the months jan+feb suggest that also. Dec 6, 2013 at 21:58
0

Here is the SQL Fiddle that demonstrates the below query:

SELECT TOP(3) NewMonth.ItemId, 
  NewMonth.Month11Sales - OldMonth.Month10Sales AS IncreaseInSales
FROM 
(
  SELECT s1.ItemId, Sum(s1.Sales) AS Month11Sales
  FROM ABC AS s1
  WHERE s1.MONTH = 11
  AND s1.YEAR = 2013
  GROUP BY s1.ItemId
) AS NewMonth
INNER JOIN 
(
  SELECT s2.ItemId, Sum(s2.Sales)  AS Month10Sales
  FROM ABC AS s2
  WHERE s2.MONTH = 10
  AND s2.YEAR = 2013 
  GROUP BY s2.ItemId
) AS OldMonth
ON NewMonth.ItemId = OldMonth.ItemId
ORDER BY NewMonth.Month11Sales - OldMonth.Month10Sales DESC

You never mentioned if you could have more than one record for an ItemId with the same Month, so I made the query to handle it either way. Obviously you were lacking the year = 2013 in your query. Once you get past this year you will need that.

0
0

Another option could be something on these lines:

SELECT top 3 a.itemid, asales-bsales increase FROM
(
(select itemid, month, sum(sales) over(partition by itemid) asales from ABC where month=2
 and year=2013) a  
INNER JOIN
(select itemid, month, sum(sales) over(partition by itemid) bsales from ABC where month=1 
 and year=2013) b
ON a.itemid=b.itemid
 ) 
ORDER BY increase desc

if you need to cater for months without sales then you can do a FULL JOIN and calculate increase as isnull(asales,0) - isnull(bsales,0)

0

You could adapt this solution based on PIVOT operator:

SET NOCOUNT ON;

DECLARE @Sales TABLE
(
    ItemID  INT NOT NULL,
    SalesDate DATE NOT NULL,
    Amount  MONEY NOT NULL
);
INSERT  @Sales (ItemID, SalesDate, Amount) 
VALUES 
(1, '2013-01-15', 333), (1, '2013-01-14', 111), (1, '2012-12-13', 100), (1, '2012-11-12', 150),
(2, '2013-01-11', 200), (2, '2012-12-10', 150), (3, '2013-01-09', 900);

-- Parameters (current year & month)
DECLARE @pYear SMALLINT = 2013, 
        @pMonth TINYINT = 1;

DECLARE @FirstDayOfCurrentMonth DATE = CONVERT(DATE, CONVERT(CHAR(4), @pYear) + '-' + CONVERT(CHAR(2), @pMonth) + '-01');

DECLARE @StartDate DATE = DATEADD(MONTH, -1, @FirstDayOfCurrentMonth), -- Begining of the previous month
        @EndDate DATE = DATEADD(DAY, -1, DATEADD(MONTH, 1, @FirstDayOfCurrentMonth)) -- End of the current month

SELECT  TOP(3) t.ItemID, 
        t.[2]-t.[1] AS IncreaseAmount
FROM
(
    SELECT  y.ItemID, y.Amount,
            DENSE_RANK() OVER(ORDER BY y.FirstDayOfSalesMonth ASC) AS MonthNum -- 1=Previous Month, 2=Current Month
    FROM
    (
        SELECT  x.ItemID, x.Amount,
                DATEADD(MONTH, DATEDIFF(MONTH, 0, x.SalesDate), 0) AS FirstDayOfSalesMonth
        FROM    @Sales x
        WHERE   x.SalesDate BETWEEN @StartDate AND @EndDate
    ) y
) z
PIVOT( SUM(z.Amount) FOR z.MonthNum IN ([1], [2]) ) t
ORDER BY IncreaseAmount DESC;

SQLFiddle demo

0

Your sample data seems to be incomplete, however, here is my try. I assume that you want to know the three items with the greatest sales-difference from one month to the next:

WITH Increases AS
(
    SELECT a1.itemid, 
           a1.sales - (SELECT a2.sales 
                       FROM   dbo.abc a2 
                       WHERE  a1.itemid = a2.itemid 
                          AND ( ( a1.year = a2.year 
                                  AND a1.month > 1 
                                  AND a1.month = a2.month + 1 ) 
                                 OR ( a1.year = a2.year + 1 
                                      AND a1.month = 1 
                                      AND a2.month = 12 ) ))AS IncreaseInSales 
    FROM   dbo.abc a1 
)
SELECT TOP 3 ItemID, MAX(IncreaseInSales) AS IncreaseInSales 
FROM Increases
GROUP BY ItemID
ORDER BY MAX(IncreaseInSales) DESC

Demo

2
  • @Tim Schmelter, In your demo shouldn't ITEMID 1 return 121. If in your example you are comparing on month to the previous month SQL Fiddle. That is if month 1 is being compared to month 2.
    – Linger
    Dec 6, 2013 at 21:21
  • No, from february to march 2013 there is a greater difference of 180. Dec 6, 2013 at 21:30
0
SELECT
  cur.[ItemId]
  MAX(nxt.[Sales] - cur.[Sales]) AS [IncreaseInSales]
FROM ABC cur
INNER JOIN ABC nxt ON (
  nxt.[Year]  = cur.[Year] + cur.[month]/12 AND
  nxt.[Month] = cur.[Month]%12 + 1
)
GROUP BY cur.[ItemId]
0

I'd do this this way. It should work in all the tagged versions of SQL Server:

SELECT TOP 3 [ItemId],
  MAX(CASE WHEN [Month] = 2 THEN [Sales] END) -
  MAX(CASE WHEN [Month] = 1 THEN [Sales] END) [Diff]
FROM t
WHERE [Month] IN (1, 2) AND [Year] = 2013
GROUP BY [ItemId]
HAVING COUNT(*) = 2
ORDER BY [Diff] DESC

Fiddle here.

The reason why I'm adding the HAVING clause is that if any item is added in only one of the months then the numbers will be all wrong. So I'm only comparing items that are only present in both months.

The reason of the WHERE clause would be to filter in advance only the needed months and improve the efficiency of the query.

An SQL Server 2012 solution could also be:

SELECT TOP 3 [ItemId], [Diff] FROM (
  SELECT [ItemId],
    LEAD([Sales]) OVER (PARTITION BY [ItemId] ORDER BY [Month]) - [Sales] Diff
  FROM t
  WHERE [Month] IN (1, 2) AND [Year] = 2013
) s
WHERE [Diff] IS NOT NULL
ORDER BY [Diff] DESC

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.