sql - 按连接表数据排序的复杂 SQL 查询

以下是样本数据,尽可能简化:

Table: items (id / manufacturer)
1 / Microsoft
2 / Microsoft
3 / Microsoft
4 / ACME
5 / Microsoft

Table: order_rows (item_id / date)
1 / 2012-12-01
1 / 2013-01-01
2 / 2013-01-02
2 / 2013-01-03
3 / 2013-01-04
3 / 2013-01-05
3 / 2013-01-06

我想要一份微软所有项目的 list ,按自 2013 年 1 月 1 日以来的购买数量排序。

因此,Microsoft 在 order_rows 中具有最多条目的项目,其中 date > 2013-01-01 将是第一个。自 2013-01-01 以来零购买的所有项目将在底部(不排除在列表之外)。

这可以通过单个查询完成吗?另外,这会不会太贵而无法实用?

所需的输出将按如下顺序排序:
3、2、1、5

最佳答案

您应该能够使用与此类似的方法连接表然后使用和 ORDER BY count(item_id) desc按照您想要的顺序获取数据:

select i.id, i.manufacturer
from items i
left join order_rows o
  on i.id = o.item_id
  and o.date > '2013-01-01'
where i.manufacturer  ='Microsoft'
group by i.id, i.manufacturer
order by count(o.item_id) desc;

见 SQL Fiddle with Demo

如果你只想要ID,那么你可以删除manufacturer从 SELECT 和 GROUP BY:
select i.id
from items i
left join order_rows o
  on i.id = o.item_id
  and o.date > '2013-01-01'
where i.manufacturer  ='Microsoft'
group by i.id
order by count(o.item_id) desc;

见 SQL Fiddle with Demo

https://stackoverflow.com/questions/16450262/

相关文章:

vbscript - 使用 VBScript 获取 Mac 地址

cassandra - Cassandra 是否是一个很好的候选数据库,因为它必须每秒支持超过 10

r - R中代数关系的笛卡尔积表

eclipse - 无法使用 sass-maven-plugin 编译 style.scss

django - 如何修复 Django 错误 : "' unicode' object has n

javascript - 如何将事件监听器添加到对象数组

scala - 由于递归隐式(上下文绑定(bind)问题?),spray-json 中的 NPE

r - 哪些参数被传递给回溯中的函数?

sql-server - 在 edmx 中重命名列的最佳方法是什么?

ember.js - Emberjs 将对象添加到 ArrayController,服务器查询是不可