TSQL Haven子句在条件条件下无法按预期执行

时间:2018-09-06 16:47:24

标签: sql-server tsql having

DECLARE @ComparisonMonth DATE
SET @ComparsionMonth '09-01-2018'

SELECT 
    Date, Sales, CustomerID 
FROM
    Database1 t1
WHERE
    Date >= CASE 
               WHEN (SELECT MAX(Date) 
                     FROM Database1 t2 
                     INNER JOIN ON t1.PlayerID = t2.PlayerID) >= DATEADD(month, -4, @ComparisonMonth) 
                    AND (SELECT MAX(Date) 
                         FROM Database1 t2 
                         INNER JOIN ON t1.PlayerID = t2.PlayerID) < DATEADD(month, -1, @ComparsionMonth) 
                  THEN DATEADD(month, -4, @ComparisonMonth)
               WHEN (SELECT MAX(Date) 
                     FROM Database1 t2 
                     INNER JOIN ON t1.PlayerID = t2.PlayerID) >= DATEADD(month, -7, @ComparisonMonth) 
                    AND (SELECT MAX(Date) 
                         FROM Database1 t2 
                         INNER JOIN ON t1.PlayerID = t2.PlayerID) < DATEADD(month, -4, @ComparsionMonth) 
                  THEN DATEADD(month, -7, @ComparisonMonth)
            END
        AND Date < CASE 
                      WHEN (Select MAX(Date) from Database1 t2 INNER JOIN on t1.PlayerID=t2.PlayerID) >= DATEADD(month, -4, @ComparisonMonth) 
                           AND (Select MAX(Date) from Database1 t2 INNER JOIN on t1.PlayerID=t2.PlayerID) < DATEADD(month, -1, @ComparsionMonth)          
                         THEN DATEADD(month, -1, @ComparisonMonth)
                      WHEN (Select MAX(Date) from Database1 t2 INNER JOIN on t1.PlayerID=t2.PlayerID) >= DATEADD(month, -7, @ComparisonMonth) 
                           AND (Select MAX(Date) from Database1 t2 INNER JOIN on t1.PlayerID=t2.PlayerID) < DATEADD(month, -4, @ComparsionMonth) 
                         THEN DATEADD(month, -4, @ComparisonMonth)
                    END

    GROUP BY
        CustomerID, Date

基本上,我只想显示特定时间段内的值,具体取决于客户上次购买商品的时间。例如,如果某个客户最近3个月内最后一次购买商品,那么我要接受最近3个月内的所有交易。取而代之的是,我要从6个月内为最后一次出现在3个月前的客户获得交易。

非常感谢您的帮助,如果您需要任何澄清,请告诉我。

1 个答案:

答案 0 :(得分:0)

我的建议是停止尝试立即实现所有目标。将查询拆分为:

1查找所需的客户。具有精确过滤条件的非常简单的查询:

DECLARE @Customers TABLE (CustomerID INT NOT NULL PRIMARY KEY, LastPurchase DATE, FirstTran DATE)

INSERT INTO @Customers(CustomerID, LastPurchase, FirstTran)
SELECT 
    CustomerID, MAX(Date), DATEADD(MM, -3, MAX(Date))
FROM Database1 d
WHERE d.date >= @ReportDate
GROUP BY CustomerID

2获取他们的交易。现在,您又有了一个很好的过滤器(加入谓词)-CustomerID。帮助服务器过滤大表-从收集的数据中查找绝对最少的日期。

DECLARE @MinDate DATE

SELECT @MinDate = MIN(FirstTran)
FROM @Customers

SELECT d.*
FROM Database1 d
INNER JOIN @Customers c
on c.CustomerID = d.CustomerID
WHERE d.Date >= c.FirstTran
  AND d.Date >= @MinDate

测试您的解决方案,如果您是否会提出一些微小的单步解决方案,请根据需要重构此代码。