這是一個SQL查詢,我很快寫了一個關於每個月PayPal購買數量的報告,數據庫是基於已導入數據的我自己的構建。根據月份重複JOIN
SELECT
Items.ItemTitle,
February.Cnt As February,
March.Cnt As March,
April.Cnt As April,
May.Cnt As May,
June.Cnt As June,
July.Cnt As July,
August.Cnt As August,
September.Cnt As September
FROM
(SELECT DISTINCT ItemTitle FROM PayPalHistory) As Items
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-02-01' AND DateTimeUtc < '2014-03-01' AND Net > 0.00
GROUP BY ItemTitle) AS February
ON Items.ItemTitle = February.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-03-01' AND DateTimeUtc < '2014-04-01' AND Net > 0.00
GROUP BY ItemTitle) AS March
ON Items.ItemTitle = March.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-04-01' AND DateTimeUtc < '2014-05-01' AND Net > 0.00
GROUP BY ItemTitle) AS April
ON Items.ItemTitle = April.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-05-01' AND DateTimeUtc < '2014-06-01' AND Net > 0.00
GROUP BY ItemTitle) AS May
ON Items.ItemTitle = May.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-06-01' AND DateTimeUtc < '2014-07-01' AND Net > 0.00
GROUP BY ItemTitle) AS June
ON Items.ItemTitle = June.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-07-01' AND DateTimeUtc < '2014-08-01' AND Net > 0.00
GROUP BY ItemTitle) AS July
ON Items.ItemTitle = July.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-08-01' AND DateTimeUtc < '2014-09-01' AND Net > 0.00
GROUP BY ItemTitle) AS August
ON Items.ItemTitle = August.ItemTitle
LEFT OUTER JOIN
(SELECT ItemTitle, COUNT(*) As Cnt FROM PayPalHistory WHERE
DateTimeUtc >= '2014-09-01' AND DateTimeUtc < '2014-10-01' AND Net > 0.00
GROUP BY ItemTitle) AS September
ON Items.ItemTitle = September.ItemTitle
ORDER BY
ItemTitle ASC
你在這裏看到一個模式? :)
有什麼辦法我可以有一個循環或一些其他的構造,以消除重複LEFT OUTER JOIN (SELECT ...)
代碼?
謝謝!
我認爲你需要一個'PIVOT'。首先使用ItemTitle,Month,Count進行表格查詢。之後,嘗試「樞軸」或使用類似的技術。像[this](http://sqlhints.com/2014/03/10/pivot-and-unpivot-in-sql-server/)。 – 2014-10-02 20:58:40