用户

时间:2016-04-19 09:13:49

标签: sql sql-server

尝试查看每个用户使用代码“MO1 + M01”进行订购的用户的最新和第二个最新消息,并按照小于或等于365天的datediff数进行过滤。

我的以下查询似乎过度排除并且不返回任何值:

注意:由于零售临时交易,很多电子邮件都是NULL或空白。

SELECT DISTINCT oh.[UID Email], c.[Offer], a2.[LatestOrderDate], a2.[OrderCount], b2.[SecondOrderDate], b2.[SecondOrderCount],
DATEDIFF(DAY,a2.[LatestOrderDate],b2.[SecondOrderDate]) Gap_Days
FROM [RBI Order Header] oh

LEFT JOIN
(SELECT DISTINCT [UID Email], [Order Date] [LatestOrderDate], [OrderCount]
FROM (SELECT ROW_NUMBER() 
    OVER(ORDER BY [Contact Order Count] DESC) AS 'OrderCount',
    [UID Email], 
    [Order Date]
    FROM [RBI Order Header]
    WHERE [UID Email] LIKE '%@%') a
WHERE OrderCount = 1
GROUP BY [UID Email], [Order Date], [OrderCount]) a2 
ON oh.[UID Email] = a2.[UID Email]

LEFT JOIN
(SELECT DISTINCT [UID Email], [Order Date] [SecondOrderDate], [SecondOrderCount]
FROM (SELECT ROW_NUMBER() 
    OVER(ORDER BY [Contact Order Count] DESC) AS 'SecondOrderCount',
    [UID Email], 
    [Order Date]
    FROM [RBI Order Header]
    WHERE [UID Email] LIKE '%@%') b
WHERE SecondOrderCount = 2
GROUP BY [UID Email], [Order Date], [SecondOrderCount]) b2 
ON oh.[UID Email] = b2.[UID Email]

LEFT JOIN
(SELECT DISTINCT LEFT(dl.[Offer No_],3) [Offer], dl.[Order No_] FROM [Rapha].dbo. [Staging Discount Line] dl
WHERE (dl.[Offer No_] LIKE 'MO1%' OR 
   dl.[Offer No_] LIKE 'M01%')) c
ON oh.[Posted Document No_]=c.[Order No_] COLLATE Latin1_General_100_CI_AI

WHERE DATEDIFF(DAY,a2.[LatestOrderDate],b2.[SecondOrderDate]) >= 365

GROUP BY oh.[UID Email], a2.[LatestOrderDate], b2.[SecondOrderDate], [Offer], DATEDIFF(DAY,a2.[LatestOrderDate],b2.[SecondOrderDate]), a2.[OrderCount], b2.[SecondOrderCount]
ORDER BY Gap_Days

2 个答案:

答案 0 :(得分:0)

尝试取出最后的where子句;

WHERE DATEDIFF(DAY, a2.[LatestOrderDate], b2.[SecondOrderDate]) >= 365

您现在是否返回任何数据?

你提到很多电子邮件都是NULL或空白而且这个字段是你加入的,你最近读过三个有价值的逻辑吗?

答案 1 :(得分:0)

您的查询太复杂而无法调试和错误编写。使用CTE编写查询。

其次,你有很多不同的分组和分组。显然,我们需要看看如何使用真实数据填充表来查找不同的根本原因。

我的查询不准确,我刚刚试图演示,如何使用CTE

;With CTE as
(
    SELECT ROW_NUMBER() 
    OVER(ORDER BY [Contact Order Count] DESC) AS rn,
    [UID Email], 
    [Order Date]
    FROM [RBI Order Header]
    WHERE [UID Email] is not null
)
,CTE1 AS
(SELECT  oh.[UID Email], c.[Offer], a2.[Order Date] as [LatestOrderDate], a2.rn as [OrderCount], b2.[Order Date] as [SecondOrderDate], b2.rn as [SecondOrderCount],
DATEDIFF(DAY,a2.[Order Date],b2.[Order Date]) Gap_Days
FROM [RBI Order Header] oh
LEFT JOIN CTE a2 ON oh.[UID Email] = a2.[UID Email]
LEFT JOIN CTE b2 ON oh.[UID Email] = b2.[UID Email]
LEFT JOIN [Rapha].dbo. [Staging Discount Line] dl ON oh.[Posted Document No_]=d1.[Order No_] COLLATE Latin1_General_100_CI_AI
where a2.rn=1 and b2.rn=1
AND (dl.[Offer No_] LIKE 'MO1%'  OR dl.[Offer No_] LIKE 'M01%') 
)

-- select * from cte //you can check here if you are getting correct output without using distinct
select * from  CTE1 where Gap_Days >= 365