我想从表格中选择公司ID,日期和数字,但此查询并未显示一些公司的0号码。
以下是查询:
SELECT c.name, date_format(e.created, '%y_%m') AS date, count(*)
FROM company c
JOIN edited e
on c.id=e.company_id AND e.created >='2016-12-13 00:00:00' AND e.created <='2017-05-20 00:00:00'
GROUP BY c.id, date
有些像这样的结果4 16_12 2 4 17_01 4 4 17_04 2 4 17_05 2 没有17_03(三月)。怎么能用0?
显示17_03答案 0 :(得分:0)
如果您的联接不符合ON子句中的值,则不会返回元组,因此您不会计算行数。如果您有一组固定的公司和日期,则可以使用UNION语句手动设置值:
(SELECT 'company_name1', 'date1', COUNT(*)
FROM company c
JOIN edited e
on c.id=e.company_id AND e.created >='2016-12-13 00:00:00' AND e.created <='2017-05-20 00:00:00')
UNION
(SELECT 'company_name2', 'date2', COUNT(*)
FROM company c
JOIN edited e
on c.id=e.company_id AND e.created >='2016-12-13 00:00:00' AND e.created <='2017-05-20 00:00:00')
#and make this for companies that not will return zero at count
UNION
(SELECT c.name, date_format(e.created, '%y_%m') AS date, count(*)
FROM company c
JOIN edited e
on c.id=e.company_id AND e.created >='2016-12-13 00:00:00' AND e.created <='2017-05-20 00:00:00'
GROUP BY c.id, date)
答案 1 :(得分:0)
SELECT c.id
, ym.y
, ym.m
, count(e.created) cnt
FROM ( SELECT @startDate := date_add(@startDate, interval 1 month) date
, year(@startDate) y
, month(@startDate) m
FROM HugeTable
JOIN ( SELECT @startDate := '2016-11-01'
, @endDate := '2017-05-01'
) months
WHERE @startDate < @endDate
) ym
LEFT JOIN edited e
ON year(e.created) = ym.y
AND month(e.created) = ym.m
LEFT JOIN company c
ON c.id = e.company_id
GROUP BY ym.y
, ym.m
, c.id
HugeTable 可以是任何具有足够记录数量的表格,作为要显示的月数。