I have a query in SQL Server in which I need it to show me only the COLUMNS that do not have 0
SELECT Codigo, Campo, Sector, SUM(Isnull([1],0)) AS [1], SUM(Isnull([2],0)) AS [2], SUM(Isnull([3],0)) AS [3], SUM(Isnull([4],0)) AS [4], SUM(Isnull([5],0)) AS [5], SUM(Isnull([6],0)) AS [6], SUM(Isnull([7],0)) AS [7], SUM(Isnull([8],0)) AS [8], SUM(Isnull([9],0)) AS [9], SUM(Isnull([10],0)) AS [10], SUM(Isnull([11],0)) AS [11]
FROM MyTabla
WHERE V.Codigo=00173 and V.Campo=1 and V.Sector=2
GROUP BY Codigo, Campo, Sector, [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]
which gives me the following result
Codigo Campo Sector 1 2 3 4 5 6 7 8 9 10 11
00173 1 2 0 0 0 0 0 0 0 27 64 15 17
The problem is that if I add (for example) to the where [1]<>0...etc, it doesn't show me any results from the row anymore.
But what I need is this:
Codigo Campo Sector 8 9 10 11
00173 1 2 27 64 15 17
mytable
Id int (pk)
Codigo varchar
Campo int
Sector int
1 float
2 float
3 float
4 float
5 float
6 float
7 float
8 float
9 float
10 float
11 float
Some preliminary clarifications:
That said, let's move on to a solution using a dynamic query, the basic idea is:
UNPIVOT
to transform the 11 columns into 11 rowsFirst the
UNPIVOT
:In
#MyTabla_Unpivot
we will have an output similar to this:And now we create the dynamic statement:
Comments:
Here a fiddle with the idea of this answer
You can do it with CASE and dynamically building the statement to execute, for example for columns 1,2 and 3 (for the rest it would be the same)
You can see this working here
I leave you a link (it is in English) where they explain a lot of casuistry of the CASE, in case what I put you does not adapt exactly to what you need.
Only complementing what was already there but without consulting the table at all times or using temporary tables.
This is just another alternative
The code can be seen here http://sqlfiddle.com/#!18/6a796/3
Cheers