重复订单+订单计数和每个订单总数

时间:2013-07-16 20:20:35

标签: sql sql-server sql-server-2008

我被要求找到2012年6月至8月期间以及2012年9月至10月期间再次购买的人。所以我这样做了。这个查询得到的结果在我检查时看起来正确。

SELECT o.BillEmail
FROM dbo.tblOrder o
WHERE (SELECT COUNT(o2.OrderDate) 
    FROM dbo.tblOrder o2 
    WHERE o2.OrderID = o.OrderID 
        AND o2.OrderDate >= '2012-06-01' AND o2.OrderDate <= '2012-08-31') > 0 
        AND (SELECT COUNT(o2.OrderDate)
            FROM dbo.tblOrder o2 
                WHERE o2.BillEmail = o.BillEmail 
                    AND o2.OrderDate >= '2012-09-01' AND o2.OrderDate <= '2012-10-31'
                    AND o2.DomainProjectID=13) > 0
    GROUP BY o.BillEmail
    ORDER BY o.BillEmail

然后他们让我找到每个客户在这两个时间段内下达的总订单,以及这些订单总数的总和。所以我刚刚添加了这些要求:

SELECT o.BillEmail, COUNT(o.OrderID) as Orders, SUM(o.Total) as 'Total'
FROM dbo.tblOrder o
WHERE (SELECT COUNT(o2.OrderDate) 
    FROM dbo.tblOrder o2 
    WHERE o2.OrderID = o.OrderID 
        AND o2.OrderDate >= '2012-06-01' AND o2.OrderDate <= '2012-08-31') > 0 
        AND (SELECT COUNT(o2.OrderDate)
            FROM dbo.tblOrder o2 
            WHERE o2.BillEmail = o.BillEmail 
                AND o2.OrderDate >= '2012-09-01' AND o2.OrderDate <= '2012-10-31'
                AND o2.DomainProjectID=13) > 0
    GROUP BY o.BillEmail
    ORDER BY o.BillEmail

然而,这仅从6月到8月的第一个指定时间段下达订单。所以它只显示从那时开始的订单和总数,而不是下半年。

如何获取两个期间的数据?

2 个答案:

答案 0 :(得分:1)

设置两个查询会不会很糟糕?

答案 1 :(得分:0)

从您的查询中看来,您似乎只对DomainProjectID = 13感兴趣,对吧?此外,如果OrderDate是日期时间并且具有一些时间值(即'2012-10-31 00:00:00.001',其大于'2012-10-31'),则可能会排除某些结果。

话虽如此,这是获取该信息的一种方法:

Select
    o.BillEmail,
    SUM(CASE WHEN o.OrderDate >= '2012-06-01' and o.OrderDate < '2012-09-01' THEN 1 ELSE 0 END) as JunToAugOrders,
    SUM(CASE WHEN o.OrderDate >= '2012-06-01' and o.OrderDate < '2012-09-01' THEN o.Total ELSE 0 END) as JunToAugTotal,
    SUM(CASE WHEN o.OrderDate >= '2012-09-01' and o.OrderDate < '2012-11-01' THEN 1 ELSE 0 END) as SepToOctOrders,
    SUM(CASE WHEN o.OrderDate >= '2012-09-01' and o.OrderDate < '2012-11-01' THEN o.Total ELSE 0 END) as SepToOctTotals,
    SUM(CASE WHEN o.OrderDate >= '2012-06-01' and o.OrderDate < '2012-11-01' THEN 1 ELSE 0 END) as JunToOctOrders,
    SUM(CASE WHEN o.OrderDate >= '2012-06-01' and o.OrderDate < '2012-11-01' THEN o.Total ELSE 0 END) as JunToOctTotals
From
    dbo.tblOrder o
Where
    o.DomainProjectID = 13
Group By
    o.BillEmail
Having
    SUM(CASE WHEN o.OrderDate >= '2012-06-01' and o.OrderDate < '2012-09-01' THEN 1 ELSE 0 END) > 0 AND
    SUM(CASE WHEN o.OrderDate >= '2012-09-01' and o.OrderDate < '2012-11-01' THEN 1 ELSE 0 END) > 0
Order By
    o.BillEmail