sql >> Base de Datos >  >> RDS >> Sqlserver

¿Cómo mostrar el resultado de la consulta en columnas (en diferentes columnas) en lugar de fila por fila?

Tal vez algo como esto:

Primero algunos datos de prueba:

CREATE TABLE Flight(FlightId  int,FlightNumber varchar(10))
CREATE TABLE FlightCapacity(ID int,FlightIdRef int,ClassIdRef int,Capacity int)
CREATE TABLE Class(ClassId int,Name varchar(10))

INSERT INTO Class VALUES(1,'Y'),(2,'A')
INSERT INTO Flight VALUES(1,123),(2,423)
INSERT INTO FlightCapacity VALUES(1,1,1,10),(2,1,2,20),(3,2,2,10)

Entonces tienes que obtener las columnas únicas como esta:

DECLARE @cols VARCHAR(MAX)
SELECT  @cols = COALESCE(@cols + ','+
                QUOTENAME('ClassNameAndCapacity'+CAST(ClassId AS VARCHAR(10))),
                QUOTENAME('ClassNameAndCapacity'+CAST(ClassId AS VARCHAR(10))))
FROM 
    Class

El delcaring y ejecutar el sql dinámico:

DECLARE @query NVARCHAR(4000)=
N'SELECT
    *
FROM
(
SELECT
    Flight.FlightNumber,
    Class.Name+CAST(FlightCapacity.Capacity AS VARCHAR(100)) AS ClassName,
    ''ClassNameAndCapacity''+CAST(Class.ClassId AS VARCHAR(10)) AS ClassAndCapacity
FROM
    Flight
    JOIN FlightCapacity
        ON Flight.FlightId=FlightCapacity.FlightIdRef
    JOIN Class
        ON FlightCapacity.ClassIdRef=Class.ClassId
) AS p
PIVOT
(
    MAX(ClassName)
    FOR ClassAndCapacity IN('[email protected]+')
) AS pvt'

EXECUTE(@query)

Y luego, en mi caso, soltaré las tablas creadas:

DROP TABLE Flight
DROP TABLE Class
DROP TABLE FlightCapacity