我有3个表:产品(prod_id,prod_name,prod_price),客户(cust_id,地址,电子邮件,姓名)和销售(sale_id,cust_id,prod_id)。
我写了一个查询来查找前100名客户(以花在任何产品上的总金额计):
SELECT TOP 100 C.name AS customer_name,
SUM(P.prod_price) AS total_spent
FROM customers C
LEFT JOIN Sales S ON C.cust_id=S.cust_id
LEFT JOIN Products P ON S.prod_id=P.prod_id
GROUP BY C.cust_id
ORDER BY total_spent DESC;
这有效(我认为)。现在,我想编写一个查询来查找每个客户购买次数最多的商品。因此,从本质上讲,我想使用第一个查询来获取姓名列表,然后找到该列表上每个人购买最多的商品。关系如何解决都没关系。
我首先尝试使用嵌套子查询编写它:
SELECT P.prod_name as best_seller,
C.name AS customer_name
FROM products P
JOIN Sales S ON P.prod_id=S.prod_id
JOIN Customers C on S.cust_id = C.cust_id
WHERE C.name IN
(SELECT TOP 100 C.name AS customer_name,
SUM(P.prod_price) AS total_spent
FROM customers C
JOIN Sales S ON C.cust_id=S.cust_id
JOIN Products P ON S.prod_id=P.prod_id
GROUP BY C.name
ORDER BY total_spent)
GROUP BY C.name, P.prod_name;
这给了我错误“无效的操作:子查询有太多的列;”。
当我尝试不在内部查询中选择total_spent时,如下所示:
SELECT P.prod_name as best_seller,
C.name AS customer_name
FROM products P
JOIN Sales S ON P.prod_id=S.prod_id
JOIN Customers C on S.cust_id = C.cust_id
WHERE C.name IN
(SELECT TOP 100 C.name AS customer_name
FROM customers C
JOIN Sales S ON C.cust_id=S.cust_id
JOIN Products P ON S.prod_id=P.prod_id
GROUP BY C.name
ORDER BY SUM(P.prod_price))
GROUP BY C.name, P.prod_name;
我得到了结果,但他们错了(这是客户的选择不同,并且他们为最常购买的产品展示相同的产品,事实并非如此)。
我想在不同情况下使用此查询来测试数据库的查询时间,因此我并不需要使其更快或更佳。我只是想不出如何做为嵌套查询。
答案 0 :(得分:0)
如果是PostgreSQL(您的查询语法指向SQL Server或Sybase),则可以使用的查询是:
var dd = {
content: [
{
alignment: 'justify',
columns: [
{
text: 'var1'
}
]
},
],
styles: {
header: {
fontSize: 18,
bold: true
},
bigger: {
fontSize: 15,
italics: true
}
},
defaultStyle: {
columnGap: 50
}
}