0

首先是我目前使用的数据:

姓名、电话、电子邮件和发票费用

我正在尝试编写一个查询来选择姓名、电话和电子邮件详细信息,其中

  • 用户(通过电子邮件识别)在过去 180 天内进行了 2 次或更多购买
  • 这 180 天内所有发票的总成本高达 500 多

以下是我到目前为止提出的 SQL,但我怀疑它是否有任何用处:

SELECT Name, Phone, Email, InvoiceCost
FROM INVOICE JOIN
    (SELECT INVOICE.Email, count(*) AS TotalCount,
     SUM(
         CASE WHEN INVOICE.InvoiceDate >= (GETDATE() - 180) 
              THEN 1 
              ELSE 0 
         END) AS LastSixMonths
     FROM INVOICE
     GROUP BY INVOICE.Email) e
ON INVOICE.Email = e.Email
WHERE (e.TotalCount > 1 AND e.LastSixMonths = 1);

我无法弄清楚如何合并总成本部分,请帮助!

4

1 回答 1

1

假设您将姓名、电话和电子邮件的独特组合视为个人客户:

SELECT Name, Phone, Email, Count(*) AS TotalCount, Sum(InvoiceCost) AS TotalCost
FROM INVOICE
GROUP BY Email, Name, Phone
WHERE DateDiff(d, InvoiceDate, GETDATE()) <= 180
HAVING Count(*) >= 2 OR Sum(InvoiceCost) > 500.0
于 2013-09-04T13:48:20.180 回答