SELECT *
FROM
(
SELECT DISTINCT
*,
CASE
WHEN ACCODE_EMFLINE = ACCODE_STLINE + ',' + ACCODE_STLINE1 THEN
ACCODE_STLINE + ',' + ACCODE_STLINE1
WHEN ACCODE_EMFLINE = ACCODE_STLINE1 + ',' + ACCODE_STLINE THEN
ACCODE_STLINE1 + ',' + ACCODE_STLINE
WHEN ACCODE_STLINE1 IS NULL THEN
ACCODE_STLINE
ELSE
''
END SIRALA
FROM
(
SELECT
(
SELECT INVOICE.FICHENO
FROM LG_201_01_INVOICE INVOICE
WHERE INVOICE.LOGICALREF = stline.INVOICEREF
) FISNO,
stline.STOCKREF,
stline.LINETYPE,
(
SELECT emuhacc.CODE
FROM LG_201_EMUHACC emuhacc
WHERE emuhacc.LOGICALREF = stline.ACCOUNTREF
) ACCODE_STLINE,
(
SELECT emuhacc.CODE
FROM LG_201_EMUHACC emuhacc
WHERE emuhacc.LOGICALREF = stline.VATACCREF
) ACCODE_STLINE1,
CASE
WHEN stline.LINETYPE = 4 THEN
STUFF(
(
SELECT DISTINCT
',' + ACCOUNTCODE
FROM LG_201_01_EMFLINE S2
WHERE S2.SOURCEFREF = stline.INVOICEREF
AND S2.LINEEXP LIKE '%' +
(
SELECT ITEMS.DEFINITION_
FROM LG_201_SRVCARD ITEMS
WHERE ITEMS.LOGICALREF = stline.STOCKREF
) + '%'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1,
1,
''
)
ELSE
STUFF(
(
SELECT DISTINCT
',' + S2.ACCOUNTCODE
FROM LG_201_01_EMFLINE S2
WHERE S2.SOURCEFREF = stline.INVOICEREF
AND S2.LINEEXP LIKE '%' +
(
SELECT ITEMS.NAME
FROM LG_201_ITEMS ITEMS
WHERE ITEMS.LOGICALREF = stline.STOCKREF
) + '%'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1,
1,
''
)
END ACCODE_EMFLINE
FROM LG_201_01_STLINE stline
WHERE BILLED = 1
) AS T
) AS C
WHERE C.SIRALA = ''
AND ACCODE_EMFLINE IS NOT NULL
AND FISNO IS NOT NULL;
FROM
(
SELECT DISTINCT
*,
CASE
WHEN ACCODE_EMFLINE = ACCODE_STLINE + ',' + ACCODE_STLINE1 THEN
ACCODE_STLINE + ',' + ACCODE_STLINE1
WHEN ACCODE_EMFLINE = ACCODE_STLINE1 + ',' + ACCODE_STLINE THEN
ACCODE_STLINE1 + ',' + ACCODE_STLINE
WHEN ACCODE_STLINE1 IS NULL THEN
ACCODE_STLINE
ELSE
''
END SIRALA
FROM
(
SELECT
(
SELECT INVOICE.FICHENO
FROM LG_201_01_INVOICE INVOICE
WHERE INVOICE.LOGICALREF = stline.INVOICEREF
) FISNO,
stline.STOCKREF,
stline.LINETYPE,
(
SELECT emuhacc.CODE
FROM LG_201_EMUHACC emuhacc
WHERE emuhacc.LOGICALREF = stline.ACCOUNTREF
) ACCODE_STLINE,
(
SELECT emuhacc.CODE
FROM LG_201_EMUHACC emuhacc
WHERE emuhacc.LOGICALREF = stline.VATACCREF
) ACCODE_STLINE1,
CASE
WHEN stline.LINETYPE = 4 THEN
STUFF(
(
SELECT DISTINCT
',' + ACCOUNTCODE
FROM LG_201_01_EMFLINE S2
WHERE S2.SOURCEFREF = stline.INVOICEREF
AND S2.LINEEXP LIKE '%' +
(
SELECT ITEMS.DEFINITION_
FROM LG_201_SRVCARD ITEMS
WHERE ITEMS.LOGICALREF = stline.STOCKREF
) + '%'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1,
1,
''
)
ELSE
STUFF(
(
SELECT DISTINCT
',' + S2.ACCOUNTCODE
FROM LG_201_01_EMFLINE S2
WHERE S2.SOURCEFREF = stline.INVOICEREF
AND S2.LINEEXP LIKE '%' +
(
SELECT ITEMS.NAME
FROM LG_201_ITEMS ITEMS
WHERE ITEMS.LOGICALREF = stline.STOCKREF
) + '%'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),
1,
1,
''
)
END ACCODE_EMFLINE
FROM LG_201_01_STLINE stline
WHERE BILLED = 1
) AS T
) AS C
WHERE C.SIRALA = ''
AND ACCODE_EMFLINE IS NOT NULL
AND FISNO IS NOT NULL;