Select top 2 sold products for each month in each department
I want to return for each department
, the top 2 sold products of each month
, in the year 2016.
My database has the following structure:
Sales(Time_id: Date, Geo_id: char(5), Prod_id: char(6), sales: Int)
Time(Time_id: Date, month: char(2), quarter: char(1), year: char(4))
Geo(Geo_id: char(5), city: varchar(20), dept: char(2), region: char(2))
Product(Prod_id: char(6), class: char(2), category: char(2))
I'm using OracleSQL.
Here's what I've done so far, for some reason I keep getting "not a GROUP BY expression":
SELECT
t.dep, t.month, t.prod, t.sales
FROM (
SELECT
Geo.dept AS dep, Time.month AS month, Sales.Prod_id AS prod, SUM(Sales.sales) AS sales,
RANK() OVER (PARTITION BY Geo.dept ORDER BY SUM(Sales.sales) DESC NULLS LAST) AS rank
FROM
Sales
INNER JOIN
Time ON Sales.Time_id = Time.Time_id
INNER JOIN
Geo ON Sales.Geo_id = Geo.Geo_id
) t
WHERE
t.rank <= 2
GROUP BY
t.month
As for the returned values, I just want the records to state the department
, the month
, the product ID
and the number of sales
.
All non-aggregated columns have to be part of the GROUP BY
clause; therefore, as commented it should be moved into the subquery. Also, you forgot to include the year = 2016
condition.
SELECT
t.dep,
t.month,
t.prod,
t.sales
FROM
(
SELECT
geo.dept AS dep,
time.month AS month,
sales.prod_id AS prod,
SUM(sales.sales) AS sales,
RANK()
OVER(PARTITION BY geo.dept
ORDER BY
SUM(sales.sales) DESC NULLS LAST
) AS rank
FROM
sales
INNER JOIN time ON sales.time_id = time.time_id
INNER JOIN geo ON sales.geo_id = geo.geo_id
WHERE
time.year = 2016
GROUP BY
geo.dept,
time.month,
sales.prod_id
) t
WHERE
t.rank <= 2