Created
December 2, 2015 11:44
-
-
Save HoffmannP/f3890296e47e00324d8d to your computer and use it in GitHub Desktop.
SQL query from hell - original from our source
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
p.sk_ID, | |
IFNULL( | |
IF( | |
!ISNULL(c.sk_ID), | |
c.sk_Verantwortlich, | |
p.sk_Verantwortlich | |
), | |
-1 | |
) AS verantwortlich, | |
DATE_FORMAT( | |
p.sk_Time, | |
IF( | |
YEAR(NOW()) = YEAR(p.sk_Time), | |
'%d.%m. %H:%i', | |
'%d.%m.%Y %H:%i' | |
) | |
) AS datum, | |
IFNULL( | |
p.sk_kt_ID, | |
IF( | |
LENGTH(TRIM(p.sk_WerWir)), | |
p.sk_WerWir, | |
'???' | |
) | |
) AS sk_WerWir, | |
p.sk_Kontakt, | |
s_Schulnummer, | |
s_ID, | |
IF( | |
ISNULL(s_NameErgaenzung), | |
s_Name, | |
CONCAT(s_Name, '<br>', s_NameErgaenzung) | |
) AS s_Name, | |
sr_KurzName AS region_kurz | |
FROM | |
s_Schulen AS s | |
JOIN | |
sk_SchulKontakte AS p ON sk_Schule = s_ID | |
# Nachtragkontakte sucht letzen Verantwortlichen raus | |
LEFT JOIN | |
sk_SchulKontakte AS c ON c.sk_RefKontakt = p.sk_ID | |
LEFT JOIN | |
sr_SchulRegionen AS sr ON sr.sr_ID = s.s_SchulRegion | |
WHERE | |
p.sk_Erledigt = 'N' AND | |
ISNULL(p.sk_RefKontakt) AND | |
( | |
ISNULL(c.sk_ID) OR | |
c.sk_Time = ( | |
SELECT MAX(c2.sk_Time) sk_time | |
FROM sk_SchulKontakte c2 | |
WHERE c2.sk_RefKontakt = c.sk_RefKontakt | |
) | |
) | |
ORDER BY | |
c.sk_Time DESC |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment