我在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条记录。特点是:
我想创建一个表格,其中包含一个唯一的电子邮件地址以及该客户最常购买的CategoryID。
所以上面的例子是:
+----------------------+------------+
| 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秒内返回结果。但是我需要在新表中使用这些数据,因为我想要使用categoryID更新另一个表。当我在子查询之后添加INTO Customer_Favourite_Categories
以将此数据添加到新表而不是仅返回结果集并运行查询时,它永远不会完成。我已经让它运行了大约45分钟,它什么也没做。
有什么方法吗?
答案 0 :(得分:2)
如果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;
答案 1 :(得分:0)
试试这个:
SELECT Distinct(Email),Max(CategoryID )
FROM Customer_Categories group by Email
答案 2 :(得分:0)
我经常使用子查询。您在“我尝试过的内容”中的查询很接近,但语法略有不同。像下面这样的东西应该得到你想要的东西。 Count在方括号中,因为它是SQL中的保留字。我在SQL中使用的间距是常规的,所以根据自己的喜好进行编辑。
SELECT Email,
CategoryID
FROM MyTable AS m,
(
SELECT Email,
MAX( [Count] ) AS mc
FROM MyTable
GROUP BY Email
) AS f
WHERE m.Email = f.Email
AND m.[Count] = f.mc;