每位销售超过1种产品的业务员的每种产品的总销售额

时间:2019-06-19 18:47:49

标签: sql sql-server

我正在尝试为这三个表编写查询,但是失败了。

我试图以具有and group by语句作为结束,但是我在联接结构中存在错误

我写了这样的查询。

SELECT a.salesman_name, p.Product_name, Sum(t.quantity) FROM SALES t
inner join SALESMAN a on t.Salesman_id =a.Salesman_id 
inner join PRODUCT p on t.Product_id = p.Product_id
GROUP BY a.salesman_name, p.Product_name
HAVING Sum(t.quantity) > 1 

但查询结果应如下所示:

+----------------+--------------+----------+
| SALESMAN_NAME  | PRODUCT_NAME | QUANTITY |
+----------------+--------------+----------+
| Ahmet Celik    | PRODUCT_A    |       25 |
| Ahmet Celik    | PRODUCT_D    |        5 |
| Ahmet Celik    | PRODUCT_E    |       10 |
| Coskun Metin   | PRODUCT_A    |       15 |
| Coskun Metin   | PRODUCT_B    |       10 |
| Ferhat Kaya    | PRODUCT_A    |        5 |
| Ferhat Kaya    | PRODUCT_C    |       12 |
| Ferhat Kaya    | PRODUCT_E    |        8 |
| Selim Albayrak | PRODUCT_C    |        5 |
| Selim Albayrak | PRODUCT_D    |        2 |
+----------------+--------------+----------+

我在sqlfiddle http://www.sqlfiddle.com/#!18/ba5ee/6中准备了数据库

在此先感谢您的帮助

3 个答案:

答案 0 :(得分:0)

您的小提琴中已经有一个数量栏。基于此,解决方案:

SELECT sm.salesman_name, p.product_name, min(quantity) as quantity
FROM Sales s
left outer JOIN Product p on p.product_id = s.product_id
left outer JOIN Salesman sm on sm.salesman_id = s.salesman_id
where quantity >= 1
Group By salesman_name, product_name

请参阅:http://www.sqlfiddle.com/#!18/ba5ee/20

答案 1 :(得分:0)

此代码将为您提供帮助。我试过了。成功了。

select distinct salesman.salesman_name, product.product_name, quantity
from sales
inner join salesman on salesman.salesman_id = sales.salesman_id
inner join product on product.product_id = sales.product_id
where salesman.salesman_name in (
select salesman.salesman_name
from sales
inner join salesman on salesman.salesman_id = sales.salesman_id
group by salesman.salesman_name
having count(salesman.salesman_name) > 1
)
and salesman.salesman_id not in(
select sales.salesman_id
from sales
group by sales.salesman_id, sales.product_id
having count(*) > 1
)

答案 2 :(得分:0)

这里有一定答案。无需使用内部联接。问是否不理解

SELECT salesman.Salesman_name,
Product.Product_name,
sum(sales.Quantity)
FROM Salesman,Product,Sales where Salesman.Salesmanid=sales.Salesmanid
and Product.Productid=Sales.Productid and 1<(SELECT count(DISTINCT Productid) 
from sales
where Salesman.Salesmanid=Sales.Salesmanid)
group by Salesman_name,Product_name