sql - 如何通过查询找到每个客户最喜欢的类别

标签 sql database ms-access ms-access-2010

我在 MS Access 中有一个表,基本上是这样的:

Table Name : Customer_Categories

+----------------------+------------+-------+
| Email                | CategoryID | Count |
+----------------------+------------+-------+
| jim@example.com      |         10 |     4 |
+----------------------+------------+-------+
| jim@example.com      |          2 |     1 |
+----------------------+------------+-------+
| simon@example.com    |          5 |     2 |
+----------------------+------------+-------+
| steven@example.com   |         10 |    16 |
+----------------------+------------+-------+
| steven@example.com   |          5 |     3 |
+----------------------+------------+-------+

此表中有 ≈ 350,000 条记录。特点是这样的:

  • Email、CategoryID 和 Count 的值重复
  • 计数是指该客户从该类别订购的次数

我想要什么

我想创建一个表,其中包含一个唯一的电子邮件地址以及该客户购买次数最多的类别 ID。

所以上面的例子是:

+----------------------+------------+
| Email                | CategoryID |
+----------------------+------------+
| jim@example.com      |         10 |
+----------------------+------------+
| simon@example.com    |          5 |
+----------------------+------------+
| steven@example.com   |         10 |
+----------------------+------------+

我尝试过的

我已经编写了一个实现我想要的查询:

SELECT main.Email, (SELECT TOP 1 CategoryID
    FROM Customer_Categories
    WHERE main.Email = Email
    GROUP BY CategoryID
    ORDER BY MAX(Count) DESC, CategoryID ASC) AS Category
FROM Customer_Categories AS main
GROUP BY main.Email;

这很有用,而且完全符合我的要求。它会在大约 8 秒内返回结果。但是我需要在新表中使用此数据,因为我想用类别 ID 更新另一个表。当我在子查询之后添加 INTO Customer_Favourite_Categories 以将此数据添加到新表而不是仅返回结果集并运行查询时,它永远不会完成。我让它运行了大约 45 分钟,但它什么也没做。

有什么办法解决这个问题吗?

最佳答案

如果 select into 不起作用,请使用 insert into:

create table Customer_Favorite_Categories (
    email <email type>,
    FavoriteCategory <CategoryId type>
);


insert into Customer_Favorite_Categories
  SELECT main.Email, (SELECT TOP 1 CategoryID
      FROM Customer_Categories
      WHERE main.Email = Email
      GROUP BY CategoryID
      ORDER BY MAX(Count) DESC, CategoryID ASC) AS Category
  FROM Customer_Categories AS main
  GROUP BY main.Email;

关于sql - 如何通过查询找到每个客户最喜欢的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18080655/

相关文章:

sql - 根据列条件求和

database - 无法删除数据库

android - 使用随机 Q 和多个 A 创建 Android 测验

sql-server - access 2007中如何使用vba刷新表列表

sql - 如何创建一个 View 表来显示同一员工的当前记录数和总数?甲骨文数据库

MySQL 错误 : key specification without a key length

sql - 创建一个函数来计算任何表中的行数

php - 对 null 调用成员函数 insert()。代码点火器

c# - 从具有链接表的 ms-access 数据库中选择一列

ms-access - 将 Excel 文件链接到 MS Access 表单