2013-07-16 194 views
0

我被要求找到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月的第一個指定時間段內下訂單。所以它只顯示從當時開始的訂單和總計,而不是下半年。

我該如何獲得它來拉兩個時期的數據?

回答

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 
+0

這看起來很棒,而且比我所要求的要多得多。我將不得不看看它包圍我的頭,哈哈/初學者 – ash

+0

很高興它爲你工作,你在堆棧溢出在這裏很好的公司。我們都是以初學者開始:) –

+0

非常感謝! :d – ash

1

設置兩個查詢會不好?

+0

我只是不知道這樣做的最佳方式,並希望建議。 :c – ash