缺少 mysql 范围内的缺失值
missing missing values in range mysql
我已经问过类似的问题,但我似乎仍然无法理解它。我的 sql 数据库
上有一列 device_create_date
2015-07-14 12:35:19
2015-07-15 12:45:37
2015-07-15 12:45:37
2015-07-16 12:35:37
2015-08-14 10:35:21
2015-08-14 12:15:36
我以周为单位汇总这些日期值,但周之间缺少值,我希望这些值刚好等于 0,以便我可以将它们与 excel 中的其他指标进行比较=34=]。我创建了一个虚拟 table "date" 来加入值,因此 select returns 0 周没有值。
这是我使用的查询,
select date.year, week(device.device_create_date), count(*)
from device
join date
on date.week_of_year=week(device.device_create_date)
where device.id_customer = 1
group by device.year, date.WEEK_OF_YEAR
order by device.year, date.week_of_year;
这是我得到的,
2010 26 7252
2010 31 3108
2010 45 7203
2010 1 9324
2010 2 7252
2010 3 2072
这是我希望它给我的回报;
2010 1 9324
2010 2 7252
2010 3 2072
2010 4 0
2010 5 0
2010 6 0
etc
顺便说一句,这些值似乎也与数据库中的计数不匹配,所以我知道我做的事情完全错了,但我不擅长这个,所以任何帮助和指导都将不胜感激。
提前致谢!!
由于您总是需要 date
table 中的值(以获取所有可能的日期)和 device
中的匹配行,因此您需要使用 date
作为来源,并使用 left join
和 device
table,因为 inner join
只会 return 在两个 table 中匹配的数据。
试试这个:
select date.year, date.week_of_year, count(device.device_create_date)
from date
left join device on date.week_of_year = week(device.device_create_date)
and device.id_customer = 1
group by date.year, date.week_of_year
order by date.year, date.week_of_year;
如果您的 table 包含超过一年的数据,您应该将年份的条件添加到联接中,这样您就不会混合多年的数据。
我已经问过类似的问题,但我似乎仍然无法理解它。我的 sql 数据库
上有一列 device_create_date2015-07-14 12:35:19
2015-07-15 12:45:37
2015-07-15 12:45:37
2015-07-16 12:35:37
2015-08-14 10:35:21
2015-08-14 12:15:36
我以周为单位汇总这些日期值,但周之间缺少值,我希望这些值刚好等于 0,以便我可以将它们与 excel 中的其他指标进行比较=34=]。我创建了一个虚拟 table "date" 来加入值,因此 select returns 0 周没有值。
这是我使用的查询,
select date.year, week(device.device_create_date), count(*)
from device
join date
on date.week_of_year=week(device.device_create_date)
where device.id_customer = 1
group by device.year, date.WEEK_OF_YEAR
order by device.year, date.week_of_year;
这是我得到的,
2010 26 7252
2010 31 3108
2010 45 7203
2010 1 9324
2010 2 7252
2010 3 2072
这是我希望它给我的回报;
2010 1 9324
2010 2 7252
2010 3 2072
2010 4 0
2010 5 0
2010 6 0
etc
顺便说一句,这些值似乎也与数据库中的计数不匹配,所以我知道我做的事情完全错了,但我不擅长这个,所以任何帮助和指导都将不胜感激。
提前致谢!!
由于您总是需要 date
table 中的值(以获取所有可能的日期)和 device
中的匹配行,因此您需要使用 date
作为来源,并使用 left join
和 device
table,因为 inner join
只会 return 在两个 table 中匹配的数据。
试试这个:
select date.year, date.week_of_year, count(device.device_create_date)
from date
left join device on date.week_of_year = week(device.device_create_date)
and device.id_customer = 1
group by date.year, date.week_of_year
order by date.year, date.week_of_year;
如果您的 table 包含超过一年的数据,您应该将年份的条件添加到联接中,这样您就不会混合多年的数据。