寻找十大畅销产品

时间:2016-12-25 07:57:51

标签: sql ruby-on-rails sql-server ruby

我需要搜索销售的前10个项目,我一直在调查,我找到了一个名为top的方法,可以使这成为可能,我尝试应用它但是我得到了这个错误:

SyntaxError (/home/luis/sites/AdvanceControld/app/models/detalleve.rb:38: syntax error, unexpected '(', expecting keyword_end
     query = select top 10('detallevet.Article')

进行此搜索的最佳方式是什么?

   def self.best_seller(params)
     query = select top 10('detallevet.Article')
          .joins('left outer join venta ON venta.Documento=detallevet.Docto and venta.RutaId=detallevet.RutaId')
          .where("(venta.RutaId = :rutaId or :rutaId = '') AND (venta.IdEmpresa = :idempresa)",{rutaId: params[:search], idempresa: params[:search0]})
     query = query.where('venta.Fecha >= ? AND venta.Fecha <= ?', (params[:search1].to_date).strftime('%Y-%m-%d'), (params[:search2].to_date).strftime('%Y-%m-%d')) if params[:search1].present? and params[:search2].present?
     query
      end

获取销售数据的表格详细(详细),此表格中包含产品。我将其与venta(销售)联系起来,因为我得到的数据就像日期一样。一个venta可以有许多detallevet和detallevet属于销售

这是detallevet架构:

  create_table "DetalleVet", primary_key: "ID", force: :cascade do |t|
    t.varchar "Article",    limit: 50
    t.integer "Docto",       limit: 4
    t.money   "Importe",                        precision: 19, scale: 4
    t.integer "RutaId",      limit: 4
    t.varchar "IdEmpresa",   limit: 50
  end

这是venta架构

  create_table "Venta", primary_key: "Id", force: :cascade do |t|
    t.integer  "RutaId",       limit: 4
    .integer  "Documento",    limit: 4
    t.datetime "Fecha"
    t.varchar  "IdEmpresa",    limit: 50
  end

1 个答案:

答案 0 :(得分:1)

我通过执行以下查询来实现解决方案,包括产品和销售数量。我希望它会帮助别人

   def self.bestseller
      joins("INNER JOIN detallevet ON productos.Clave = detallevet.Articulo")
             .select("detallevet.Articulo, COUNT(Articulo) as count, productos.Producto")
              .group("detallevet.Articulo, productos.Producto").order("count DESC").limit(10)
    end