Sql查询为单个不同的客户ID选择记录

时间:2012-04-11 09:41:08

标签: sql

我已经按照以下方式为客户编写了一份销售查询:

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
那么如何应对呢?

2 个答案:

答案 0 :(得分: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个订单的东西,因为你已经分组了多个订单

答案 1 :(得分:1)

您需要了解GROUP BY的含义。 如果您按customerId进行分组,则只有一个客户,因为所有数据都是grouped

您希望按orderid进行分组并在结果集上显示orderid?如果您有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