I have a problem when generating a query using the PIVOT function of SQL - server 2008. The query itself has no disadvantages, since the values it throws are correct. For EMP3 the query throws totally NULL or 0, this is correct, but I need to generate a dynamic query that does not show the column whose sum is 0.
The query is detailed below:
SELECT
[Fecha], [Cantidad],
ISNULL([EMP1],0) AS [EMP1],
ISNULL([EMP2],0) AS [EMP2],
ISNULL([EMP3],0) AS [EMP3],
ISNULL([EMP4],0) AS [EMP4]
FROM(
SELECT
CONVERT (VARCHAR(10),de.FECHA, 103) As [Fecha],
ci.COD_EMP,
SUM(bs.IMPORTE) as [Importe],
SUM (CASE WHEN bs.CANTIDAD <> 0 THEN 1 ELSE 0 END) AS [Cantidad]
FROM TABLA1 lc (NOLOCK)
JOIN TABLA2 bs (NOLOCK) ON lc.ID1 = bs.ID1
JOIN TABLA3 so (NOLOCK) ON bs.soc_id = so.soc_id
JOIN TABLA4 ci (NOLOCK) ON ci.COD_EMP = '<<funcion que arroja COD_EMP sobre lc.ID>>'
JOIN TABLA5 de (NOLOCK) ON bs.ID2 = de.ID2
JOIN TABLA6 co (NOLOCK) ON bs.ID3 = co.ID3
JOIN TABLA7 cb (NOLOCK) ON co.CTA = cb.CTA
JOIN TABLA8 su (NOLOCK) ON cb.SUC = su.SUC
WHERE co.CO_ID = '11111'
AND bs.ESTADO in (6,7)
AND de.FECHA BETWEEN CONVERT (DATETIME,'2017-10-24') AND CONVERT (DATETIME,'2017-10-27')
AND '<<FUNCION>>' <> so.COD_EMP
AND lc.SERV = bs.SERV
GROUP BY FECHA , '<<FUNCION>>'),ci.COD_EMP
) nuevatabla
PIVOT (SUM(IMPORTE) FOR COD_EMP in ([EMP1], [EMP2],[EMP3], [EMP4])) AS pvt
ORDER BY 1
The result is the following:
Fecha Cantidad EMP1 EMP2 EMP3 EMP4
24/10/2017 1 0.00 5.96 0.00 0.00
24/10/2017 4 66.71 0.00 0.00 0.00
24/10/2017 8 0.00 0.00 0.00 4.05
How can I write this query to avoid showing columns that are completely 0 ?. As an extra comment, the EMP3 column can have data depending on the date and any other column can not.