简体   繁体   中英

Pivot in t-sql without aggregate or exact match of columns

I've seen a few answers on this, but none seem to fit

I have a large DB with many tables that are essentially the same as each other - however, at some point in the past new columns have been added/renamed/removed.

I am trying to use INFORMATION_SCHEMA.COLUMNS to get a list of columns, per target table, but in a pivot format - so the table name is across the top and Ordinal Position as the rows.

Using these tables

CREATE TABLE tbl1 (
  Id int
, Code int
, GroupName varchar(25)
, Amount money
, OutstandingAmount money
, DataDate date
)
ON [PRIMARY]

CREATE TABLE tbl2 (
      Id int
    , Code int
    , CompanyName varchar(25)
    , CompanyRegistrationDate date
    , Amount money
    , OutstandingAmount money
    , DataDate date
)
ON [PRIMARY]

CREATE TABLE tbl3 (
      Id int
    , Code int
    , CustomerId varchar(10)
    , CustomerName varchar(25)
    , Amount money
    , OutstandingAmount money
    , DataDate date
)
ON [PRIMARY]

Then the following query gets me the data, and I can c&p in excel to line up the columns.

select
    c.ORDINAL_POSITION
    , c.TABLE_NAME
    , c.COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME LIKE 'tbl%'


ORDINAL_POSITION    TABLE_NAME  COLUMN_NAME
1   tbl1    Id
2   tbl1    Code
3   tbl1    GroupName
4   tbl1    Amount
5   tbl1    OutstandingAmount
6   tbl1    DataDate
1   tbl2    Id
2   tbl2    Code
3   tbl2    CompanyName
4   tbl2    CompanyRegistrationDate
5   tbl2    Amount
6   tbl2    OutstandingAmount
7   tbl2    DataDate
1   tbl3    Id
2   tbl3    Code
3   tbl3    CustomerId
4   tbl3    CustomerName
5   tbl3    Amount
6   tbl3    OutstandingAmount
7   tbl3    DataDate

However, in reality there are 100's of tables (system created) so c&p is not really a sensible option.

My issue is also that the number of columns is inconsistent.

I've tried a pivot, but can't work out what to pivot on! I am trying to acheive this...

ORDINAL_POSITION    tbl1                tbl2                        tbl3
    1               Id                  Id                          Id
    2               Code                Code                        Code
    3               GroupName           CompanyName                 CustomerId
    4               Amount              CompanyRegistrationDate     CustomerName
    5               OutstandingAmount   Amount                      Amount
    6               DataDate            OustandingAmount            OustandingAmount
    7               NULL                DataDate                    DataDate

Use can also use catalog views sys.tables or sys.columns instead of INFORMATION_SCHEMA.COLUMNS

Try this:-

    DECLARE @cols AS NVARCHAR(MAX);
    DECLARE @query AS NVARCHAR(MAX);

  select @cols = STUFF((SELECT distinct  ',' +
                    QUOTENAME(t.name) 
                  FROM sys.tables t 
                  inner join sys.columns c 
                  on c.object_id=t.object_id 
                  where t.name like 'tb%'
                  FOR XML PATH(''), TYPE
                 ).value('.', 'NVARCHAR(MAX)') 
                    , 1, 1, '');
 --Select @cols
 SELECT @query =
               'SELECT *
                FROM
                ( 
                select t.name as TableName,
                      c.name ColumnName,
                      row_number() over (PARTITION BY T.OBJECT_id order by T.NAME) as ID
                from sys.tables t 
                inner join sys.columns c 
                on c.object_id=t.object_id 
                    where t.name like ''tb%''
                ) AS t
                PIVOT 
               (
                MAX(ColumnName) 
                FOR TableName IN( ' + @cols + ' )' +
               ' ) AS p ; ';
      execute(@query);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM