【问题标题】:retrieve data from a database the most sold products by branch从数据库中检索分店最畅销产品的数据
【发布时间】:2020-07-30 22:03:40
【问题描述】:

我试图在我的项目中获得 Branch 最畅销的产品,但我不知道我的 Sql 查询有什么问题。

这是我的数据库的架构:

DIM_SOUS_CAT 表是产品表,每个产品都按 Branch 和 Category 分类

DIM_CAT 数据:

DIM_BRANCHE 数据

DIM_SOUS_CAT 数据是产品

FAIT_VENTE数据,即销售列表

我写了一个 sql 查询,但它不起作用。这是查询:

select vf.id_branche, vf.id_categorie, count(*) 
from vente_fact vf 
GROUP by vf.id_branche, vf.id_categorie  
HAVING count(*) = (  
   SELECT max(COUNT(*)) 
   FROM vente_fact vf2  
   GROUP by vf2.id_branche, vf2.id_categorie 
) 

请有任何建议!

【问题讨论】:

  • 你不能嵌套聚合函数max(COUNT(*))
  • 是的,你是对的!但我需要获取 Branch 已售出的最大产品数量

标签: mysql sql mysql-workbench mysql-error-1064


【解决方案1】:

你快到了。就问题而言,您只需要修复子查询:

  • 需要关联到外部查询

  • 你不能嵌套聚合表达式,比如MAX(COUNT(*));这将需要额外级别的聚合 - 相反,您可以 order bylimit

我建议:

select 
    vf.id_branche, 
    vf.id_categorie, 
    count(*) no_ventes
from vente_fact vf 
group by vf.id_branche, vf.id_categorie 
having count(*) = (
    select count(*) 
    from vente_fact vf2 
    where vf2.id_branche = vf1.id_branche
    order by count(*) desc
    limit 1 
)

请注意,如果您运行的是 MySQL 8.0,则使用窗口函数可以更有效地完成此操作:

select id_branche, id_categorie, no_ventes
from (
    select 
        id_branche, 
        id_categorie, 
        count(*) no_ventes,
        rank() over(partition by id_branche order by count(*) desc) rn
    from vente_fact vf 
    group by id_branche, id_categorie 
) t
where rn = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多