Sqlserver
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Sqlserver

SQL Server:Làm cách nào để tôi có thể nhóm nhiều giá trị hàng thành các cột riêng biệt?

Đây là một cách xoay vòng động:

declare @table table (Email varchar(64), Phone varchar(16), ID varchar(3))
insert into @table
values

('[email protected]','555-5555','001'),
('[email protected]','555-5556','001'),
('[email protected]','555-5557','001'),
('[email protected]','555-5558','001'),
('[email protected]','333-5556','002'),
('[email protected]','444-5556','002'),
('[email protected]','777-5556','002')


select
    Email
    ,Phone
    ,ID
    ,row_number() over (partition by ID order by Phone) as RN
into #staging
from 
    @table




DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column 
SELECT @ColumnName= ISNULL(@ColumnName + ',','') 
       + QUOTENAME(RN)
FROM (SELECT DISTINCT RN FROM #staging) AS RN

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
  N'SELECT Email, ID, ' + @ColumnName + '
    FROM #staging
    PIVOT(MAX(Phone) 
          FOR RN IN (' + @ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

drop table #staging

Nếu bạn chỉ mong đợi 3, như bạn đã nêu, bạn có thể bỏ qua động ...

declare @table table (Email varchar(64), Phone varchar(16), ID varchar(3))
insert into @table
values

('[email protected]','555-5555','001'),
('[email protected]','555-5556','001'),
('[email protected]','333-5556','002'),
('[email protected]','444-5556','002'),
('[email protected]','777-5556','002')

;with cte as(
select
    Email
    ,Phone
    ,ID
    ,row_number() over (partition by ID order by Phone) as RN
from 
    @table)

select
    Email
    ,max(case when RN = 1 then Phone end) as Phone1
    ,max(case when RN = 2 then Phone end) as Phone2
    ,max(case when RN = 3 then Phone end) as Phone3
    ,ID
from
    cte
group by
    Email
    ,ID



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Đệ quy tối đa 100 đã hết trước khi lỗi hoàn thành câu lệnh hiển thị trong Truy vấn SQL

  2. Các tính năng mới của SQL Server 2019

  3. Khóa chính kết hợp trong biến loại Bảng

  4. Sao lưu tự động máy chủ SQL

  5. Loại bỏ và tạo lại cơ sở dữ liệu trong Microsoft SQL Server