Transpose a set of rows as columns in SQL Server 2000

后端 未结 5 2067
无人及你
无人及你 2020-12-17 23:13

Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)? I was befuddled because this facility is available in MS-Access but not in

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-17 23:29

    The cursor method described is probably the least SQL-like to use. As mentioned, SQL 2005 and on has PIVOT which works great. But for older versions and non-MS SQL servers, the Rozenshtein method from "Optimzing Transact-SQL" (edit: out of print, but avail. from Amazon: http://www.amazon.com/Optimizing-Transact-SQL-Advanced-Programming-Techniques/dp/0964981203), is excellent for pivoting and unpivoting data. It uses point characteristics to turn row based data into columns. Rozenshtein describes several cases, here's one example:

    SELECT
        RowValueNowAColumn = 
           CONVERT(varchar,
               MAX(
              SUBSTRING(myTable.MyVarCharColumn,1,DATALENGTH(myTable.MyVarCharColumn)
           * CHARINDEX(sa.SearchAttributeName,'MyRowValue'))))
    FROM
        myTable
    

    This method is a lot more efficient than using case statements and works for a variety of data types and SQL implementations (not just MS SQL).

提交回复
热议问题