我是一个相对新手,我现在已经和这个人争斗太久了 - 所以请任何人帮忙!
我有一个表格,可以接收不同类型开发项目的查询(dev_enquiry),我正在创建一个动态图表来显示每个开发项目每天的查询次数。我加入了日历表,其中包含一列日期,以便在没有查询时可以获得0值。
这个SQL给了我我想要的东西,但它适用于所有的开发
SELECT calendar.datefield AS DATE, COUNT(de_id) AS enquiries
FROM `calendar`
LEFT JOIN dev_enquiry ON DATE(dev_enquiry.de_date_created) = calendar.datefield)
WHERE calendar.datefield BETWEEN (
SELECT MIN(DATE(de_date_created))
FROM dev_enquiry
)
AND (SELECT MAX(DATE(de_date_created)) FROM dev_enquiry)
GROUP BY DATE
ORDER BY DATE DESC
2012-11-08 3
2012-11-07 0
2012-11-06 2
2012-11-05 1
2012-11-04 3
我希望按开发类型过滤掉结果,但在当天没有针对该特定开发的查询时仍保留空值。
以下过滤结果但不给我空值:
SELECT cal.datefield AS DATE, COUNT(t.de_id) AS enquiries
FROM (
SELECT * FROM dev_enquiry as d LEFT JOIN calendar as c ON (DATE(d.de_date_created) = c.datefield)
WHERE d.de_dev_name = 'Green') as t
LEFT JOIN calendar as cal ON (cal.datefield = DATE(t.de_date_created))
WHERE (cal.datefield BETWEEN (SELECT MIN(DATE(t.de_date_created))
FROM dev_enquiry) AND (SELECT MAX(DATE(de_date_created)) FROM dev_enquiry))
GROUP BY DATE ORDER BY DATE DESC
2012-11-08 1
2012-11-06 2
2012-11-05 1
2012-11-04 1
2012-11-07的结果不见了
答案 0 :(得分:2)
这里的技巧是使用完整的日历表引导您的查询,然后加入不完整(缺少某些天)的摘要表。另请注意IFNULL
将(null)结果转换为零。
SELECT cal.datefield AS date,
IFNULL(s.enquiries, 0) AS enquiries
FROM calendar as cal
LEFT JOIN (
SELECT count(*) enquiries,
de_date_created
FROM dev_enquiry
WHERE de_dev_name = 'Green'
GROUP BY de_date_created
) s on s.de_date_created = cal.datefield
WHERE cal.datefield
BETWEEN (SELECT MIN(de_date_created) FROM dev_enquiry)
AND (SELECT MAX(de_date_created) FROM dev_enquiry)
ORDER BY datefield DESC
这是一个SQL小提琴。 http://sqlfiddle.com/#!2/2db68/12/0
答案 1 :(得分:1)
也许我误解了这个问题,为什么不在第一个查询示例中在左连接中添加AND de_dev_Name = 'Green'
?
SELECT calendar.datefield AS d, COUNT(dev_enquiry.de_id) AS enquiries
FROM calendar
LEFT JOIN dev_enquiry ON (dev_enquiry.de_date_created = calendar.datefield AND de_dev_name = 'Green')
WHERE calendar.datefield BETWEEN
(SELECT MIN(DATE(de_date_created)) FROM dev_enquiry)
AND (SELECT MAX(DATE(de_date_created)) FROM dev_enquiry)
GROUP BY d
ORDER BY d DESC