USE FAST2;

-- Företag som parameter?

SELECT DISTINCT o.OBJ_OBJNR,
                o.OBJ_OBJTYP,
                o.OBJ_ADR,
                o.OBJ_HNAMN,
                o.OBJ_MOMSMARK,
                r.AVR_MOMSPL,
                p.PKO_PKT_MOMSKOD
  FROM OBJ o
 INNER JOIN AVT h ON o.OBJ_AVTNR = h.AVT_AVTNR
 INNER JOIN AVR r ON h.AVT_AVTNR = r.AVR_AVTNR
 INNER JOIN PKO p ON o.OBJ_OBJNR = p.PKO_OBJNR
 WHERE o.OBJ_OBOTYP NOT LIKE 'P%'
   AND o.OBJ_HNAMN NOT IN ('PROJEKT', 'RENOVERING')
   --AND o.OBJ_FTGNR = 'EHB'
   AND o.OBJ_OBOTYP NOT LIKE 'G%'
   AND o.OBJ_AVTNR != '999999999'
   AND p.PKO_PKTYP NOT IN ('3614', 'VVMJUST', 'KVMJUST', 'ELBJUST', 'VVMSCHAB', 'KVMSCHAB', 'TFVATT', 'T880')
   AND p.PKO_PKTYP NOT LIKE 'HBO%'
   AND p.PKO_HTYP = 'HYRA'
   AND (p.PKO_TOMDAT >= CONVERT(VARCHAR(8), GETDATE(), 112) OR p.PKO_TOMDAT = 'TV')
   AND o.OBJ_OBJNR = r.AVR_OBJNR
   AND NOT (o.OBJ_MOMSMARK = 'N' AND r.AVR_MOMSPL = 'N' AND (p.PKO_PKT_MOMSKOD = '0' OR p.PKO_PKT_MOMSKOD = 'MOMSFR'))
   AND NOT (o.OBJ_MOMSMARK = 'J' AND r.AVR_MOMSPL = 'J' AND p.PKO_PKT_MOMSKOD = 'FULLMO')
   AND (
    OBJ_IAKTDAT IS NULL
    OR OBJ_IAKTDAT = ''
    OR OBJ_IAKTDAT >= CONVERT(
      VARCHAR(8),
      GETDATE(),
      112
    )
  )
  AND (
    OBJ_FORSALJDATUM IS NULL
    OR OBJ_FORSALJDATUM = ''
    OR OBJ_FORSALJDATUM >= CONVERT(
      VARCHAR(8),
      GETDATE(),
      112
    )
  )
ORDER BY o.OBJ_OBJNR