查看一个日期范围内的数据,并从另一个日期范围开始计算

时间:2015-08-20 20:26:59

标签: sql-server date-range having

我一直在查询,我试图获取有关在特定日期范围内新获得的客户的信息。

我需要获得一份客户名单,这些客户在一年的前6个月内(一直以来)下了第一笔订单。然后,我需要获得他们的发票总额,第一个发票日期,最后发票日期以及过去6个月的订单数量。

我使用了HAVING条款来确保我只关注那个在6个月内首次下单的客户,但由于我们现在已经过了这段时间,因此总发票信息和订单计数信息将包括之后的订单这次。我考虑在“最后一个发票日期”的HAVING条款中加入限制,但之后我将淘汰第一个订单日期在6个月块中的客户,但之后又订购了。我不知道接下来该做什么,也没有找到类似问题的运气。以下是我到目前为止的情况:

SELECT c.customer, MAX(c.name) AS Name, 
    SUM(
        CASE WHEN im.debit = 0
        THEN im.amount * -1
        ELSE im.amount
        END
    ) AS TotalInvoiceAmount,
    MIN(
          im.date) AS FirstInvoiceDate,
    MAX(
        im.date) AS LastInvoiceDate,
    COUNT(DISTINCT om.[order]) AS OrderCount
FROM invoicem im
INNER JOIN customer c ON im.customer = c.customer
FULL JOIN orderm om ON im.customer = om.customer
WHERE im.amount <> 0
GROUP BY c.customer
HAVING MIN(im.date) BETWEEN '01-01-2015' AND '06-30-2015'
ORDER BY c.customer

1 个答案:

答案 0 :(得分:1)

您可以将前6个月的资格作为子查询。这也可以作为CTE

declare @startDate date = dateadd(month,-6,getdate())

SELECT c.customer, MAX(c.name) AS Name, 
    SUM(
        CASE WHEN im.debit = 0
        THEN im.amount * -1
        ELSE im.amount
        END
    ) AS TotalInvoiceAmount,
    MIN(
          im.date) AS FirstInvoiceDate,
    MAX(
        im.date) AS LastInvoiceDate,
    COUNT(DISTINCT om.[order]) AS OrderCount
FROM invoice im
INNER JOIN (SELECT customer from invoice
            GROUP BY customer
            HAVING MIN(date) BETWEEN '01-01-2015'
            AND '06-30-2015') im2
ON im.customer = im2.customer
INNER JOIN customer c ON im.customer = c.customer
FULL JOIN orderm om ON im.customer = om.customer
WHERE im.amount <> 0
AND im.date >= @startdate
GROUP BY c.customer
ORDER BY c.customer