如何获得最多订单的供应商列表

时间:2017-12-27 14:00:42

标签: mysql sql ruby-on-rails postgresql

关系

Supplier - >与orders

的一对多关系
| suppliers                             |
| ----------                            |
| id | name | archived (bool) | user_id |

| orders                        |
| ----------------              |
| id | supplier_id | creator_id |

期望

现在,我想获取给定supplierssupplier.user_id的热门orders.creator_id列表,而supplier不应该是archived(请查看预期结果)在问题的最后)。

这就是我想要的:

  • 供应商ORDER BY maximum(count(orders.supplier_id))
  • 其中supplier.archived = false
  • 其中supplier.user_id = 2
  • 其中orders.creator_id = 1

不成功的逮捕

这是我的失败,我不知道如何在此查询中添加供应商条件。

  select supplier_id, COUNT(*) as count_suppliers 
  from orders 
  where creator_id = 2
  group by orders.supplier_id
  order by count_suppliers desc

所以这就是我想要的

suppliers

| id  | user_id | archived |
| --- | ---------  | -------  |
| 1   | 2          | false    |
| 2   | 2          | false    |
| 3   | 2          | false    |
| 4   | 2          | false    |
| 5   | 2          | true     |

orders

| id | creator_id | supplier_id  |
| -- | ---------  | ------------ |
| 1  | 1          | 1            |
| 2  | 1          | 1            |
| 3  | 1          | 1            |
| 4  | 1          | 1            |
| 5  | 1          | 2            |
| 6  | 1          | 2            |
| 7  | 1          | 3            |
| 8  | 1          | 4            |
| 9  | 1          | 4            |
| 10 | 1          | 4            |
| 11 | 1          | 5            |

expected output

| supplier_id | supplier_count |
| 1           | 4              |
| 4           | 3              |
| 2           | 2              |
| 3           | 1              |

最后通过参考Vamsi的回答,在这里你可以找到RAW SQL版本和ActiveRecord(Rails)版本的解决方案来解决这个问题:

RAW SQL VERSION

SELECT o.supplier_id, COUNT(*) AS count_suppliers 
FROM suppliers s
JOIN orders o ON s.id=o.supplier_id
WHERE s.user_id=2 
AND s.archived=FALSE
AND o.creator_id=2
GROUP BY o.supplier_id
ORDER BY count_suppliers DESC
LIMIT 5

ActiveRecord (Rails) Version

Supplier
  .joins(:orders)
  .where(user_id: 2, archived: false, orders: { creator_id: 2 })
  .group("orders.supplier_id")
  .order("count_all DESC")
  .limit(limit)
  .count

2 个答案:

答案 0 :(得分:1)

您可以(function(root, factory) { if (typeof define === 'function' && define.amd && define.amd.dust === true) { define(['dust-linkedin'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('dust-linkedin')); // module.exports = factory; // <<--- This is working on v8 } else { factory(root.dust); } }(this, function (dust) { ... }); 表格并计算。

join

答案 1 :(得分:0)

select top 1 supplier_id, COUNT(*) as count_suppliers 
from purchase_orders 
where orders.creator_id = 1
And supplier.archived = false
And supplier.user_id = 2
group by purchase_orders.supplier_id
order by COUNT(*) desc