我几天来一直试图修复我的查询。它应该按月分组,如果没有找到记录则返回0。这是我的疑问:
SELECT
school_id,
IF(school="Utah Valley University","Schoo1",
IF(school="Weber State University","School2", school)) school,
online,
pif_price,
COUNT(pif_price),
pif_price,
payment_plans.id AS Payment,
COUNT(IFNULL(x1.Month,0))
FROM users
INNER JOIN students
ON users.id = students.user_id
INNER JOIN students_terms
ON students.id = students_terms.student_id
INNER JOIN terms
ON students_terms.term_id = terms.id
INNER JOIN courses
ON terms.course_id = courses.id
INNER JOIN schools
ON courses.school_id = schools.id
INNER JOIN payment_plans
ON students_terms.payment_plan_id = payment_plans.id
INNER JOIN (SELECT
DISTINCT MONTH(enroll_date) AS Month,
enroll_date
FROM students_terms
GROUP BY Month ASC) AS x1
ON students_terms.enroll_date = x1.enroll_date
WHERE
NOT pif_price = 229
AND NOT pif_price = 429
AND NOT pif_price = 1199
AND students_terms.enroll_date >="2017-01-01"
AND students_terms.enroll_date < CURDATE()
GROUP BY
month
如您所见,我试图从嵌套表中获取数字1-12。
即使这样,查询也会运行,但不会带来任何数据。
我可以通过取出嵌套表来重新获取数据,如下所示:
SELECT
school_id,
IF(school="Utah Valley University","School1",
IF(school="Weber State University","School2", school)) school,
online,
pif_price,
COUNT(pif_price),
payment_plans.id AS Payment,
CONCAT(MONTH(students_terms.enroll_date), "/", YEAR(students_terms.enroll_date)) AS Enroll_Date
FROM users
INNER JOIN students
ON users.id = students.user_id
INNER JOIN students_terms
ON students.id = students_terms.student_id
INNER JOIN terms
ON students_terms.term_id = terms.id
INNER JOIN courses
ON terms.course_id = courses.id
INNER JOIN schools
ON courses.school_id = schools.id
INNER JOIN payment_plans
ON students_terms.payment_plan_id = payment_plans.id
WHERE
NOT pif_price = 229
AND NOT pif_price = 429
AND NOT pif_price = 1199
AND enroll_date >="2017-01-01"
AND enroll_date < CURDATE()
GROUP BY
YEAR(enroll_date),
MONTH(enroll_date),
pif_price
在这里研究我能够发现,如果制作一个“月表”并加入它,那将解决我的问题。问题是,我没有权限向DB添加表。这就是为什么我试图让它与嵌套的“月表”一起工作。
有没有办法让这段代码无需添加“月份表?”
感谢您的帮助!