Und hier noch der finale Code für den Fall, dass jemand ein ähnliches Problem hat. Die beiden Fehlerhinweise sind zwar immer noch da. Aber er funktioniert: BestenDank für die freundliche Unterstützung von castorp und ukulele.
SQL:
WITH t1 AS (
SELECT m1.mem_usr_id, m1.mem_rol_id,
YEAR(m1.mem_begin) AS mem_year,
1 AS mem_active
FROM adm_members m1
WHERE m1.mem_rol_id IN (74,75) AND EXISTS (SELECT m2.mem_usr_id from adm_members m2 where m2.mem_rol_id = 74 AND m1.mem_usr_id = m2.mem_usr_id AND YEAR(mem_end) >= YEAR(NOW()))
UNION ALL
SELECT m1.mem_usr_id, m1.mem_rol_id,
(CASE WHEN YEAR(m1.mem_end) = '9999' THEN year(NOW()) ELSE YEAR(m1.mem_end) END) AS mem_year,
-1 AS mem_active
FROM adm_members m1
WHERE m1.mem_rol_id IN (74,75) AND EXISTS (SELECT m2.mem_usr_id from adm_members m2 where m2.mem_rol_id = 74 AND m1.mem_usr_id = m2.mem_usr_id AND YEAR(m2.mem_end) >= YEAR(NOW()))
), t2 AS (
SELECT mem_usr_id, mem_rol_id,
mem_year,
sum(mem_active) OVER (PARTITION BY mem_usr_id ORDER BY mem_year) AS mem_active
FROM t1
), t3 AS (
SELECT *,
lag(mem_active) OVER (PARTITION BY mem_usr_id ORDER BY mem_year) AS lag_mem_active
FROM t2
), t4 AS (
SELECT *,
(CASE WHEN mem_active = 0 THEN lag(mem_year) OVER (PARTITION BY mem_usr_id ORDER BY mem_year) ELSE NULL END) AS lag_mem_year
FROM t3
WHERE mem_active = 1
AND ( lag_mem_active IS NULL
OR lag_mem_active = 0 )
OR ( mem_active IS NULL
OR mem_active = 0 )
AND lag_mem_active = 1
), user_info as (
select v.usd_usr_id,
v.usd_value as vorname,
n.usd_value as nachname
from adm_user_data v
join adm_user_data n on v.usd_usr_id = n.usd_usr_id and n.usd_usf_id = 1
where v.usd_usf_id = 2
), t5 AS (
SELECT mem_usr_id, sum(mem_year - lag_mem_year + 1) - 1 as mem_sum
from t4
GROUP BY mem_usr_id
)
SELECT mem_usr_id, u.vorname, u.nachname, mem_sum, CONCAT(u.nachname, ' ' , u.vorname, ', ') AS sort,
CASE
WHEN 30 - mem_sum + Year(Now()) >= Year(Now()) THEN CONCAT(30 - mem_sum + Year(Now()), ' Kantonaler Veteran')
WHEN 35 - mem_sum + Year(Now()) >= Year(Now()) THEN CONCAT(35 - mem_sum + Year(Now()), ' Eidgenössischer Veteran')
WHEN 50 - mem_sum + Year(Now()) >= Year(Now()) THEN CONCAT(50 - mem_sum + Year(Now()), ' Kantonaler Ehren-Veteran')
WHEN 60 - mem_sum + Year(Now()) >= Year(Now()) THEN CONCAT(60 - mem_sum + Year(Now()), ' CISM Veteran')
WHEN 70 - mem_sum + Year(Now()) >= Year(Now()) THEN CONCAT(70 - mem_sum + Year(Now()), ' Eidgenössischer Ehren-Veteran')
END AS jubi
from t5
join user_info u on usd_usr_id = mem_usr_id
HAVING (LEFT(jubi,4) <= Year(Now())+5)
ORDER BY jubi ASC, sort ASC;