我有一个查询按月和年计算所有工作ID号,然后使用jpgraph创建过去13个月的图表。除非7月份没有工作ID号码,否则它的效果很好,因此图表完全会跳过7月份。
查询结果:
5
16
15
11
3
12
4
8
2
9
13
12
期望的结果:
5
16
15
11
3
12
0
4
8
2
9
13
12
正如您所看到的,我需要(0)零才能使我的图表正常工作,但是由于7月份没有工作ID号,我的查询只是跳过它。这是我的疑问:
SELECT COUNT( WORK_ID_NUM ) AS count,
DATE FROM SERVICE_JOBS
WHERE (DATE BETWEEN '$lastyear' AND '$date')
AND JOB_TYPE LIKE 'Street Light'
GROUP BY YEAR( DATE ), MONTH( DATE )
ORDER BY DATE
答案 0 :(得分:0)
要让您的查询返回7月份的行,您需要在其中添加包含7月的行。你可以创建一个表格,其中包含$ lastyear和$ date之间的所有日期,然后从那里连接到SERVICE_JOB。
SELECT COUNT( WORK_ID_NUM ) AS count,
allDates.DATE
FROM AllDates
Left outer join SERVICE_JOB
on AllDates.DATE = SERVICE_JOB.DATE
WHERE (AllDates.DATE BETWEEN '$lastyear' AND '$date') AND
(SERVICE_JOB.WORK_ID_NUM is NULL OR JOB_TYPE LIKE 'Street Light')
GROUP BY YEAR( AllDates.DATE ), MONTH( AllDates.DATE )
ORDER BY AllDates.DATE
在SQL Server中,根据$ lastyear和$ date制作一个可以为你填充AllDates的Common Table Expression非常容易。不确定MySql。
答案 1 :(得分:0)
SELECT IFNULL(count,0) as count,theDate as Date
FROM
(SELECT @month := @month+INTERVAL 1 MONTH as theDate
FROM service_jobs,(SELECT @month:='$lastyear' - INTERVAL 1 MONTH)as T1
LIMIT 13)as T2
LEFT JOIN
(SELECT COUNT(WORK_ID_NUM)as count,DATE
FROM service_jobs
WHERE (DATE BETWEEN '$lastyear' AND '$date')
AND JOB_TYPE LIKE 'Street Light'
GROUP BY YEAR(DATE), MONTH(DATE)) T3
ON (YEAR(theDate) = YEAR(DATE) AND MONTH(theDate) = MONTH(DATE))
ORDER BY theDate;