2017-07-19 185 views
1

過去兩天我一直在試圖弄清楚這一點。這是我認爲很容易的事情,但是我不能在我的生活中找出所需的SQL查詢。我找到了一些相關的問題/答案,但不完全是我遇到的問題。過去7天的MySQL計數記錄按0記錄分組,

我試圖獲得本週過去7天的記錄計數,並按分支位置對其進行分組,並且在沒有找到記錄時也包括0。每個人都說的一件事是,我需要生成一個日曆/日期助手錶,然後加入它。我已經完成了這項工作,現在我有一個日曆表,日期在2000-01-012040-01-01之間。

這裏是我的表結構如下所示:

Records | location | date | thing | |----------|------------|---------| | Branch 1 | 2017-04-01 | Thing 1 | | Branch 2 | 2017-04-03 | Thing 2 | | Branch 1 | 2017-04-03 | Thing 3 | | Branch 1 | 2017-04-01 | Thing 4 | | Branch 3 | 2017-04-01 | Thing 5 | | Branch 3 | 2017-04-02 | Thing 6 | | Branch 1 | 2017-04-02 | Thing 7 | | Branch 2 | 2017-04-07 | Thing 8 |

讓我們假設它目前2017-04-07。請注意,並非所有包含2017-04-012017-04-07的日期都在記錄表中,這就是我需要日曆助手錶的原因。話雖這麼說,我試圖讓下面的輸出:

Output | location | date | count(things)| |----------|------------|--------------| | Branch 1 | 2017-04-01 | 2 | | Branch 1 | 2017-04-02 | 1 | | Branch 1 | 2017-04-03 | 1 | | Branch 1 | 2017-04-04 | 0 | | Branch 1 | 2017-04-05 | 0 | | Branch 1 | 2017-04-06 | 0 | | Branch 1 | 2017-04-07 | 0 | | Branch 2 | 2017-04-01 | 0 | | Branch 2 | 2017-04-02 | 0 | | Branch 2 | 2017-04-03 | 1 | | Branch 2 | 2017-04-04 | 0 | | Branch 2 | 2017-04-05 | 0 | | Branch 2 | 2017-04-06 | 0 | | Branch 2 | 2017-04-07 | 1 | | Branch 3 | 2017-04-01 | 1 | | Branch 3 | 2017-04-02 | 1 | | Branch 3 | 2017-04-03 | 0 | | Branch 3 | 2017-04-04 | 0 | | Branch 3 | 2017-04-05 | 0 | | Branch 3 | 2017-04-06 | 0 | | Branch 3 | 2017-04-07 | 0 |

所以,即使有零條記錄,我還是要顯示該位置的線路和日期(過去7天) 。這是否可以實現?

這裏是我一直插科打諢與查詢:

SELECT 
    `records`.`location`, 
    `calendar`.`date`, 
    COUNT(`records`.`thing`) AS `count` 
FROM `records` 
    RIGHT JOIN `calendar` ON `records`.`date` = `calendar`.`date` 
WHERE `calendar`.`date` >= '2017-04-01' AND `calendar`.`date` <= '2017-04-07' 
GROUP BY `calendar`.`date`, `records`.`location` 
ORDER BY `records`.`location` ASC, `calendar`.`date` ASC 

SELECT 
    `records`.`location`, 
    `date`.`ymd`, 
    COUNT(`records`.`thing`) AS `count` 
FROM (
    SELECT 
     `calendar`.`date` AS `ymd` 
    FROM `calendar` 
    WHERE `calendar`.`date` >= '2017-04-01' AND `calendar`.`date` <= '2017-04-07' 
) `date` 
    LEFT JOIN `records` ON `date`.`ymd` = `records`.`date` 
GROUP BY `records`.`location`, `date`.`ymd` 

兩個查詢給我這甚至還沒有接近我正在尋找相同的結果對於。

請幫忙!

+0

你有分支機構/位置表嗎? – Sal

回答

1

這不僅是日期,你需要一個完整的清單,但分支機構也是如此。我添加了一個包含所有位置的派生表,並將其交叉添加到以前的結果集中。另外,選擇列表中的位置字段和group by子句必須來自此派生表。

SELECT 
    t.`location`, 
    `calendar`.`date`, 
    COUNT(`records`.`thing`) AS `count` 
FROM `records` 
RIGHT JOIN (`calendar` 
JOIN (select distinct location from records) t) ON `records`.`date` = `calendar`.`date` and t.location=records.location 
WHERE `calendar`.`date` >= '2017-04-01' AND `calendar`.`date` <= '2017-04-07' 
GROUP BY `calendar`.`date`, t.`location` 
ORDER BY `records`.`location` ASC, `calendar`.`date` ASC 
+0

完美!謝謝! –