我对SQL Sever非常陌生,所以如果问题措辞奇怪,我会道歉。我正在做家庭作业,这就是问题:
“经理想要知道每个客户的电子邮件地址,号码或订单以及购买的总金额。创建一个摘要查询,为每个有订单的客户返回这三个项目。”
我查询了所有数据,问题是当我从每个客户提取数据时,它会显示每个订单的项目数量,我需要将这些项目合并到一个列中。这是我到目前为止的查询(再次,总noob,请原谅任何糟糕的语法等)
SELECT EmailAddress,
ItemPrice - DiscountAmount * Quantity AS TotalPurchaseAmount,
COUNT(*) AS OrderQty
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID
GROUP BY Orders.CustomerID,
OrderItems.ItemPrice, OrderItems.DiscountAmount,
OrderItems.Quantity,
Customers.EmailAddress;
以下是我得到的结果集的一小部分:
Email Address OrderTotal OrderQty
allan.sherwood@yahoo.com 253.15 2
allan.sherwood@yahoo.com 839.30 2
allan.sherwood@yahoo.com 1208.16 2
barryz@gmail.com 303.79 4
christineb@solarone.com 479.60 2
david.goldstein@hotmail.com 299.00 2
david.goldstein@hotmail.com 489.30 1
david.goldstein@hotmail.com 479.60 1
正如你所看到的,我有几个订单需要每个电子邮件一起排成一行,我已经查找并寻找答案,但我唯一能找到的是如何查找重复项并忽略它们,不要结合他们的数据。任何帮助都非常感谢,非常感谢花时间阅读这篇文章:)如果我的问题没有意义,请告诉我,以便我可以清除我可能使用的任何不良措辞!
答案 0 :(得分:1)
只需GROUP BY CustomerID, EmailAddress
:
SELECT
c.EmailAddress,
SUM((i.ItemPrice - i.DiscountAmount) * Quantity) AS TotalPurchaseAmount,
COUNT(*) AS OrderQty
FROM Customers c
INNER JOIN Orders o
ON c.CustomerID = o.CustomerID
INNER JOIN OrderItems i
ON o.OrderID = i.OrderID
GROUP BY
c.CustomerID, c.EmailAddress
附加说明:为表格使用别名
答案 1 :(得分:1)
您需要更改公式并从选择查询中删除不想分组的列。 例如,您的查询应该是这样的
SELECT EmailAddress,
--do your aggregation here
blah AS TotalPurchaseAmount,
COUNT(*) AS OrderQty
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
JOIN OrderItems ON Orders.OrderID = OrderItems.OrderID
GROUP BY Orders.CustomerID,
Customers.EmailAddress;