SQL查询以检索每个用户的总订单数

时间:2019-03-03 07:41:21

标签: sql-server tsql

  

编写一条SQL命令,以检索所有客户的姓氏和名字以及他们下的订单的订单号…

CustDetails表格:http://prntscr.com/msicdp OrderDetails表格:http://prntscr.com/msichp

我正在尝试显示CustDetails(表)中所有用户的列表,并增加一列“ TotalOrders”,该列计算每个用户从COUNT(*)中的OrderDetails(表)中获得的订单数量,但是看起来我不知道我在做什么。

我尝试过将LEFT JOIN与COUNT(*) AS [Total Orders]配对使用,无论尝试如何,我都会遇到各种错误

SELECT DISTINCT CustDetails.*, OrderDetails.CustRef,COUNT(*) AS [Order_number]
FROM CustDetails
LEFT JOIN OrderDetails ON CustDetails.CustRef = OrderDetails.CustRef
GROUP BY CustDetails.FName
--SELECT CustDetails.CustRef, count(*) AS NUM
--  FROM CustDetails GROUP BY CustRef

1 个答案:

答案 0 :(得分:0)

您不能将*GROUP BY放在一起。如果您使用的是GROUP BY,则GROUP BY子句中应包含所有未聚合的列。

您需要像下面这样编写查询。

select c.CustRef,
       c.LName,
       c.Fname,
       sum(case when od.CustRef is null then 0 else 1 end) TotalOrders
from CustDetails c
left join OrderDetails od on od.CustRef =c.CustRef
group by c.CustRef ,c.LName, C.Fname

如果您需要所有列,可以尝试使用以下内容而不使用GROUP BY

select *,
       (select count(*) from OrderDetails od where  od.CustRef =c.CustRef) TotalOrders
from CustDetails c

使用PARTITION BY

的另一种方法
select * from
(
select c.*,
        sum(case when od.CustRef is null then 0 else 1 end) over(partition by c.CustRef) as TotalOrders,
        row_number() over (partition by c.CustRef order by (select 1)) rn
from CustDetails c
left join OrderDetails od on od.CustRef =c.CustRef
) t
where rn=1