DROP VIEW LD0VAAYDocuments
;

CREATE VIEW LD0VAAYDocuments
AS
SELECT
T41.*,
Q01.KLARTEXT TYP_T, 
0 BLANKETT,
CASE WHEN EXISTS(SELECT 'X' FROM LD0VYC C WHERE C.AEVERKNR = T41.AGARNR AND T41.AGARTYP = 42 AND C.TMARK = 1) THEN 1 ELSE 0 END AS TMARK
FROM LD0V0T41 T41 
LEFT JOIN LD0V0Q01 Q01 
ON T41.ANTDOKTYP = Q01.KOD AND Q01.KODTYP = 'ANTTYP'
WHERE T41.ANTDOKTYP > 0

UNION ALL
SELECT
T41.*,
Q01.KLARTEXT TYP_T, 
Q01.XNUM4 BLANKETT,
CASE WHEN T41.AGARTYP = 22 THEN 1 ELSE 0 END AS TMARK
FROM LD0V0T41 T41 
LEFT JOIN LD0V0Q01 Q01 
ON T41.DOKTYP = Q01.KOD AND Q01.KODTYP = 'TYPDOK' 
WHERE T41.DOKTYP > 0

UNION ALL
SELECT
T41.*,
'' TYP_T, 
0 BLANKETT,
0 TMARK
FROM LD0V0T41 T41 
WHERE T41.DOKTYP = 0 AND T41.ANTDOKTYP = 0
;