在过去的两天里,我一直试图解决这个问题。这是我认为很容易的事情,但我不能为我的生活找出所需的SQL查询。我发现了一些相关的问题/答案,但并不完全是我遇到的问题。
我正在尝试获取一周中过去7天的记录数,并按分支位置对其进行分组,并且在没有找到记录时也包括0。每个人都说的一件事是我需要生成一个日历/日期助手表并离开加入它。我已经离开了,我现在有一个日历表,其日期介于2000-01-01
和2040-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-01
和2017-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 :(得分: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