Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

mengelompokkan dan mengganti kolom dan baris

Anda dapat melakukannya dengan PIVOT dinamis dan ROW_NUMBER() fungsi:

DECLARE @cols AS VARCHAR(1000),
        @query  AS VARCHAR(8000)
SELECT @cols = STUFF((SELECT ',' +   QUOTENAME(Name) 
                    FROM (SELECT DISTINCT Name
                          FROM #test
                          )sub
                    ORDER BY Name
                    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)') 
                    ,1,1,'')
PRINT @cols

SET @query = '
WITH cte AS (SELECT DISTINCT *
             FROM  #test)
    ,cte2 AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Apt)RowRank
             FROM  cte)
SELECT * 
FROM  cte2 
PIVOT (max(Apt) for Name in ('[email protected]+')) p
            '
EXEC (@query)

SQL Fiddle - Daftar Berbeda, Urutan Tertentu

Sunting:Jika Anda tidak ingin daftarnya berbeda, hilangkan cte pertama di atas, dan jika Anda ingin tetap memesan sewenang-wenang, ubah ORDER BY ke (SELECT 1) :

DECLARE @cols AS VARCHAR(1000),
        @query  AS VARCHAR(8000)
SELECT @cols = STUFF((SELECT ',' +   QUOTENAME(Name) 
                    FROM (SELECT DISTINCT Name
                          FROM #test
                          )sub
                          ORDER BY Name
                    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)') 
                    ,1,1,'')
PRINT @cols

SET @query = '
WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY (SELECT 1))RowRank
             FROM  #test)
SELECT * 
FROM  cte 
PIVOT (max(Apt) for Name in ('[email protected]+')) p
            '
EXEC (@query)

SQL Fiddle - Daftar Lengkap, Urutan Sewenang-wenang

Dan terakhir, jika Anda tidak menginginkan RowRank di hasil Anda, cukup gunakan kembali @cols variabel di SELECT . Anda :

SET @query = '
WITH cte AS (SELECT *,ROW_NUMBER() OVER(PARTITION BY Name ORDER BY (SELECT 1))RowRank
             FROM  #test)
SELECT '[email protected]+' 
FROM  cte 
PIVOT (max(Apt) for Name in ('[email protected]+')) p
            '
EXEC (@query)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara membagi CSV dari satu kolom ke baris di tabel baru di MSSQL 2008 R2

  2. Simpan array byte di server sql

  3. Menjelajahi SQL Server 2014 PILIH KE Paralelisme

  4. /Konflik kunci asing SQL Server dalam pernyataan multi nilai?

  5. Pengaruh petunjuk NOLOCK dalam pernyataan SELECT