我有3个表:wp_names,wp_payments,wp_renewals。我在student_id中使用了JOIN。
SELECT s.student_id AS 'Student ID'
,s.student_first_name AS 'First Name'
,@numberofregistrations := count(DISTINCT p.payment_id) as 'Number of Registrations'
,@latestregdate := date(max(p.date)) AS 'Latest Registration'
,@renewals := IF(count(DISTINCT r.date) >= 1, count(DISTINCT r.date), '') as Renewals
,@latestrenewal := date(max(r.date)) AS 'Latest Renewal'
,@latestpayment := IF(@renewals >= 1, @latestrenewal, @latestregdate) AS 'Latest P.'
,DATE_ADD(@latestpayment,INTERVAL 12 MONTH) AS 'Due Renewal'
FROM wp_names AS s
LEFT JOIN wp_payments AS p ON s.student_id = p.student_id
LEFT JOIN wp_renewals AS r ON s.student_id = r.student_id
GROUP BY s.student_id, p.payment_id, p.registration, p.date
这是我得到的结果。请注意,最新付款都是错误的,而且到期续订也是错误的。
如何使用我创建的变量?我想在IF语句中使用它们,例如:
IF(@renewals> = 12,@ onsrenewal,@ onsstregdate)。
还有:
DATE_ADD(@latestpayment,INTERVAL 12 MONTH)
最后,我无法弄清楚如何获得计数(DISTINCT p.payment_id)来给出正确的结果“2”。而不是这样,它将学生ID“2”加倍,并且对于两个条目都计为1。
总之,这两个问题是:
我很感激你的帮助。