SQL显示特定字段多次显示的条目

时间:2013-09-04 13:23:52

标签: sql sql-server

首先,这里是我目前正在使用的数据:

姓名,电话,电邮和InvoiceCost

我正在尝试编写一个选择名称,电话和电话的查询。电子邮件详情

  • 用户(通过电子邮件确定)在过去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);

我无法弄清楚如何纳入总成本部分,请帮忙!

1 个答案:

答案 0 :(得分: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