sql >> Databasteknik >  >> RDS >> Sqlserver

Hämta rader som kolumner i sqlserver 2008

Prova detta :

SELECT fromcity
      ,[Vskp]=isnull([Vskp],0)
      ,[Hyd]=isnull([Hyd],0)
      ,[Chennai]=isnull([Chennai],0)
FROM (  SELECT  fromcity ,tocity,Dist
        FROM DistanceTable
        union

        SELECT  tocity,fromcity ,Dist
        FROM DistanceTable

     ) AS ET
PIVOT
(max(dist) FOR tocity  IN ([Vskp],[Hyd],[Chennai])
) AS PT 

SQL-fiol

Uppdatering: Använd dynamisk SQL för variabelt antal städer enligt nedan:

DECLARE
    @cols VARCHAR(MAX),
    @IsNullCols VARCHAR(MAX),
    @query VARCHAR(MAX)


SELECT
    @cols = STUFF((
            SELECT DISTINCT ', [' + tocity + ']'
            FROM (SELECT  tocity FROM DistanceTable
                    union 

                    SELECT  fromcity FROM DistanceTable)a  

            FOR XML PATH('')
          ), 1, 2, '');
print @cols;

SELECT
    @IsNullCols = STUFF((
            SELECT DISTINCT ', ['+tocity+']=IsNull([' + tocity + '],0)'
            FROM (SELECT  tocity FROM DistanceTable
                    union 

                    SELECT  fromcity FROM DistanceTable)a 

            FOR XML PATH('')
          ), 1, 2, '');

print @IsNullCols;          

set @query = 'SELECT fromcity
      ,'+ @IsNullCols +'
FROM (
        SELECT  fromcity ,tocity,Dist
        FROM DistanceTable
        union 

        SELECT  tocity,fromcity ,Dist
        FROM DistanceTable

     ) AS ET
PIVOT
(max(dist) FOR tocity  IN ('[email protected]+')
) AS PT '

exec(@query)


  1. SQL Server:Ta reda på standardvärdet för en kolumn med en fråga

  2. Hur får man ett float-resultat genom att dividera två heltalsvärden med T-SQL?

  3. Introduktion till SQL-kommandon

  4. Drivrutin:[email protected] returnerade null för URL... Under implementeringen av vårstart till Heroku