在SQL Server中,如果一张表包含客户(Customer)、金额(Amount)和业务员(Salesperson)字段,并且每个客户可能关联多个业务员,如何设计查询以显示每行客户资料及其对应的全部业务员及其金额?
时间: 2024-11-22 17:37:38 浏览: 17
在SQL Server中,如果你有一张名为`Transactions`的表,它有`CustomerID`, `Amount`, 和`SalespersonID`三个字段,而每个客户可以有多条记录对应不同的业务员,你可以使用`UNION ALL`或者`GROUP BY`和`CROSS APPLY`来获取每个客户的全部业务员及金额。假设你有一个`Employees`表,包含`EmployeeID`和`EmployeeName`,那么可以这样做:
```sql
SELECT Customer.CustomerInfo, e.EmployeeName, SUM(T.Amount) as TotalAmount
FROM Customers AS Customer
LEFT JOIN Transactions AS T ON Customer.CustomerID = T.CustomerID
LEFT JOIN Employees as e ON T.SalespersonID = e.EmployeeID
GROUP BY Customer.CustomerInfo, e.EmployeeName
UNION ALL
SELECT '合计', NULL, SUM(T.Amount) as TotalAmount
FROM Customers AS Customer
JOIN Transactions AS T ON Customer.CustomerID = T.CustomerID
GROUP BY Customer.CustomerID
```
这个查询首先按客户分组,显示每个客户的每个业务员及其总金额。接着,它添加一个额外的行,表示客户的总金额,这行的`EmployeeName`为NULL,表明它是汇总信息。
阅读全文