SQL Server 08 - pivot - Change Column Name

b5lpy0ml  于 2023-03-28  发布在  SQL Server
关注(0)|答案(2)|浏览(132)

I have this code:

SELECT * FROM(
   SELECT A.Id,
          B.Note,
          C.Value,
          C.Ammount
   FROM Table1 A
   LEFT JOIN Table2 B ON A.Id = B.Id
   LEFT JOIN Table3 C ON B.Id = c.Id AND B.Name = C.Name
   INNER JOIN(
      SELECT Name, LName, AxValue, Code, Number
      FROM Table Ax
      Where (Code = 80 AND Name = 'Bo') AS D ON D.AxValue = C.Value)
)AS Node1
PIVOT(
   SUM(Ammount)
   FOR Value IN ([1], [2])
)AS Node2

and the result is something like this:

Id   Note   1    2
--------------------
01   ok    500  100

Is there any way to rename the last two columns with names(Ex1,Ex2) instead of numbers(1,2)?

tkqqtvp1

tkqqtvp11#

Replace :

SELECT * FROM(
...

By

SELECT Id, Note, [1] as Ex1, [2] as Ex2 FROM(
...

It is always better to replace * by the columns you need. You can alias them with as .

You can find more information here: Using Table Aliases

And here under column_ alias : SELECT Clause

xdnvmnnf

xdnvmnnf2#

Try this:

SELECT Id, Note, [1] as Ex1, [2] as Ex2 FROM(
   SELECT A.Id,
          B.Note,
          C.Value,
          C.Ammount
   FROM Table1 A
   LEFT JOIN Table2 B ON A.Id = B.Id
   LEFT JOIN Table3 C ON B.Id = c.Id AND B.Name = C.Name
   INNER JOIN(
      SELECT Name, LName, AxValue, Code, Number
      FROM Table Ax
      Where (Code = 80 AND Name = 'Bo') AS D ON D.AxValue = C.Value)
)AS Node1
PIVOT(
   SUM(Ammount)
   FOR Value IN ([1], [2])
)AS Node2

Instead of using * you need to specify the name of your column.

相关问题