0

对于购买者电子邮件地址列表,我试图为每个购买者返回一行,其中包含“1stOrderDate”、“2ndOrderDate”、“3rdOrderDate”和“TotalNumberofOrders”列

我曾尝试在子查询的 WHERE 子句中使用 ROW_Number 函数,但它报告说 WHERE 子句中不允许使用窗口函数,因此我将不胜感激地收到有关如何填写下面 ???s 的任何帮助!

SELECT 
PT.email AS 'Email',
MIN(OT.orderdate) AS '1stOrderDate',
???               AS '2ndOrderDate',
???               AS '3rdOrderDate',
COUNT(DISTINCT OT.order_reference) AS 'TotalNumberOfOrders'    

FROM dbo.Orders AS OT
JOIN dbo.Purchaser AS PT ON OT.account_reference = PT.account_reference

GROUP BY PT.Email
4

1 回答 1

1

您可以使用row_number()条件聚合来做到这一点:

SELECT PT.email,
       MAX(CASE WHEN seqnum = 1 THEN OT.OrderDate END) as OrderDate_1,
       MAX(CASE WHEN seqnum = 2 THEN OT.OrderDate END) as OrderDate_2,
       MAX(CASE WHEN seqnum = 3 THEN OT.OrderDate END) as OrderDate_3,
       COUNT(DISTINCT OT.order_reference) AS TotalNumberOfOrders   
FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY account_reference ORDER BY o.orderdate) as seqnum
      FROM dbo.Orders o
     ) OT JOIN
     dbo.Purchaser PT
     ON OT.account_reference = PT.account_reference
GROUP BY PT.Email

几点注意事项:

  • 不要对列别名使用单引号。相反,选择不需要转义的列名。
  • 对于segnum = 1逻辑,您可以使用MIN(),但我认为一致性在这里是一个好处。

编辑:

我的猜测是问题出在 aaccount_referenceemail. 尝试这个:

SELECT email,
       MAX(CASE WHEN seqnum = 1 THEN OT.OrderDate END) as OrderDate_1,
       MAX(CASE WHEN seqnum = 2 THEN OT.OrderDate END) as OrderDate_2,
       MAX(CASE WHEN seqnum = 3 THEN OT.OrderDate END) as OrderDate_3,
       COUNT(DISTINCT OT.order_reference) AS TotalNumberOfOrders   
FROM (SELECT o.*, ROW_NUMBER() OVER (PARTITION BY pt.email ORDER BY o.orderdate) as seqnum
      FROM dbo.Orders o JOIN
           dbo.Purchaser PT
           ON OT.account_reference = PT.account_reference
     ) OT 
GROUP BY PT.Email
于 2014-12-10T12:57:02.990 回答