0

我写了一个分组客户销售的查询,如下所示:

SELECT customerid,
SUM (salestax1)As total_salestax1,
SUM(total_payment_received) As total_payment_recieved,
COUNT (orderid)as order_qty,
SUM(paymentamount)As paymentamount
 FROM Orders_74V94W6D22$
WHERE orderdate between '7/6/2011 16:35' and '2/3/2012 11:53'    
GROUP BY customerid 

但此查询仅显示 5 个字段,但我需要显示以下字段:

orderid    billingcompanyname    billingfirstname    billinglastname    
billingcountry    shipcountry    paymentamount creditcardtransactionid    
orderdate    creditcardauthorizationdate    orderstatus    
total_payment_received    tax1_title salestax1

那么如何处理呢?

4

2 回答 2

1

要选择有关客户的更多信息,您需要将查询用作子查询,例如:

Select distinct c.[column1], c.[column2], c.[column3], tbl.*
From Orders_74V94W6D22$ c inner join (
 SELECT customerid,
SUM (salestax1)As total_salestax1,
SUM(total_payment_received) As total_payment_recieved,
COUNT (orderid)as order_qty,
SUM(paymentamount)As paymentamount
 FROM Orders_74V94W6D22$
WHERE orderdate between '7/6/2011 16:35' and '2/3/2012 11:53'    
GROUP BY customerid 
) as tbl on tbl.customerid = c.customerid

但是你不能在逻辑上选择关于 1 个订单的东西,因为你已经对多个订单进行了分组

于 2012-04-11T09:45:49.603 回答
1

您需要了解 GROUP BY 的含义。如果您按 customerId 分组,您将只有一个客户,因为所有数据都grouped在其中。

你想如何分组orderidorderid在你的结果集上显示?如果您有 10 个订单 ID,您希望结果中有 10 行吗?如果是,很好,按它分组,但我认为这不是你想要的

编辑:

好吧,这不是一个好主意,你的表结构是错误的,我认为你不完全理解一个组的方式,但我认为这个查询会得到你的结果:

 SELECT customerid, 
 (select top 1  [column1] from Orders_74V94W6D22$ where customerid = ORD.customerid),
 (select top 1  [column2] from Orders_74V94W6D22$ where customerid = ORD.customerid),
 (select top 1  [column3] from Orders_74V94W6D22$ where customerid = ORD.customerid),
 SUM (salestax1)As total_salestax1, 
 SUM(total_payment_received) As total_payment_recieved, 
 COUNT (orderid)as order_qty, 
 SUM(paymentamount)As paymentamount
 FROM Orders_74V94W6D22$  ORD
 WHERE orderdate between '7/6/2011 16:35' and '2/3/2012 11:53' 
 GROUP BY customerid 
于 2012-04-11T10:11:25.403 回答