选择每个部门每个月最畅销的2种产品

2022-04-13 00:00:00 sql oracle greatest-n-per-group

我想退货每个department,每个<2-1]>在2016年销售的产品。

我的数据库结构如下:

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))

我正在使用OracleSQL。

以下是我到目前为止所做的工作,由于某种原因,我总是得到&NOT 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

至于返回值,我只希望记录显示departmentmonthproduct IDnumber of sales


解决方案

所有非聚集列都必须是GROUP BY子句的一部分;因此,正如所注释的那样,它应该移入子查询。此外,您忘记包括year = 2016条件。

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, time.month
                 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

相关文章