﻿select 
Betrieb,  
Stufe2, 
FAGNR, 
FTYPE,
KNDNR,
KNAME, 
Stufe5, 
REDAT, 
O500_HW2BUCHGBETR,  
FLDAT as FLDAT_von, 
FLDAT as FLDAT_bis, 
FLDAT, 
O500_MAHNSTUFE, 
Next_MAHNSTUFE, 
O500_HW2BETR_OFFEN, 
OPDAT,
O500_BELEGNR1,
Ktelf, 
Kstra, 
Kdplz, 
Kdort,  
Bemerkung, 
Wiedervorlage, 
Bemerkung_2, 
Bearbeitet, 
Mahnen, 
`User`, 
Aenderungsdatum,  
User_2, 
Aenderungsdatum_u2,
KZALA, 
Versicherung,
Rechtsanwalt,
Reklamation, 
Selbstbeteiligung, 
SelbstbeteiligungBetrag, 
Mwst, 
MwstBetrag,
Reserve_1,
ReservE_3,
round((unix_timestamp(current_date())-unix_timestamp(FLDAT))/86400) as "Faell_Tage",
case 
  when (round((unix_timestamp(current_date())-unix_timestamp(FLDAT))/86400) < 14 ) then '0-2 Wochen'  
  when (round((unix_timestamp(current_date())-unix_timestamp(FLDAT))/86400) < 28 )then '2-4 Wochen' 
  when (round((unix_timestamp(current_date())-unix_timestamp(FLDAT))/86400) < 42 )then '4-6 Wochen' 
  when (round((unix_timestamp(current_date())-unix_timestamp(FLDAT))/86400) >= 42 ) then '> 6 Wochen'   
  else 'n.v.' 
end as "Wochen"

from fm_aha_report

where stufe2 IN ('SC','TZ')

and

case
  when [userid] IN ('') then stufe2 IN ('SC')
  when [userid] IN ('') then stufe2 IN ('TZ')
  else 1 end
  
and 

case
  when [userid] IN ('carville') then betrieb IN ('GÖG')
  when [userid] IN ('acimovic') then betrieb IN ('WTB')
  when [userid] IN ('samueller') then betrieb IN ('LEH')
  when [userid] IN ('preis') then betrieb IN ('LEH','GÖG')
  when [userid] IN ('cfj') then betrieb IN ('LEH','GÖG','WTB')
  when [userid] IN ('rolle') then betrieb IN ('GÖG','WTB')
  else 1 end


order by FLDAT asc