0

我被要求找到在 2012 年 6 月至 2012 年 8 月之间以及在 2012 年 9 月至 2012 年 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 月的第一个指定时间段拉取订单。所以它只显示从那时起的订单和总支出,而不是下半年。

我如何让它同时提取两个时期的数据?

4

2 回答 2

1

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

于 2013-07-16T20:51:40.990 回答
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
于 2013-07-16T21:04:30.080 回答