在查询中一起使用GROUP BY和ROW_NUMBER

时间:2018-02-02 19:57:17

标签: sql-server-2008

在我的查询中,我使用rownumber在客户ID上有一个分区,但我希望它按照emailaddress分组。有办法吗?

我有两个表,包含以下列: 顾客: <ion-card *ngFor="let cData of CList" [style.background]="cData.Color"> <!-- --> </ion-card>

订单: EmailAddress,CustomerId

OrderDate,CustomerId,OrderId,PaymentAmount

注意:我的数据在select t.EmailAddress, COUNT(t.OrderID) AS NumOrders, SUM(t.PaymentAmount) as Total_Ordered, max (case when t.rn = 2 then t.OrderDate end) as previous_date, max (case when t.rn = 1 then t.Orderdate end) as last_date from ( select c.EmailAddress, o.OrderDate, o.OrderID , o.PaymentAmount, row_number() over (partition by c.CustomerID order by OrderDate desc) as rn from Customers c Join Orders o ON c.CustomerID=o.CustomerID )t group by t.EmailAddress; 时是唯一的,而不是EmailAddress

0 个答案:

没有答案