Sql Pivot水平

时间:2016-06-27 09:11:03

标签: sql pivot

下午全部,

试图找出如何在没有聚合的情况下进行旋转,因为存在字母数字值。还有另一个术语吗?

这是我拥有的数据:

Id          Name
1Bravo      John
1Bravo      Smith
2Charlie    Dave
2Charlie    Billy

我希望实现的目标:

Id       Name    Name
1Bravo   John    Smith   

用Bravo显示结果

我还没有通过支点

获得任何好处
Select ID, Name
From Table
Pivot (
Max(ID) For ID Like ('Bravo%') 

感谢任何帮助

由于

2 个答案:

答案 0 :(得分:0)

这将根据给定Id的名称数量动态构建查询。

--Create Sample Data
CREATE TABLE myTable
    ([Id] varchar(8), [Name] varchar(5))
;
INSERT INTO myTable
    ([Id], [Name])
VALUES
    ('1Bravo', 'John'),('1Bravo', 'Smith'),    
    ('2Charlie', 'Dave'),('2Charlie', 'Billy'),('2Charlie', 'Bobby')
;


DECLARE @Id VARCHAR(8) = '1Bravo',
        @Sql NVARCHAR(MAX),
        @SelCols NVARCHAR(MAX),
        @PivCols NVARCHAR(MAX)

--Build Select and Pivot columns dynamically based on the number of Names for the given @Id
SELECT  @SelCols = COALESCE(@SelCols + ',','') + QUOTENAME(ROW_NUMBER() OVER (ORDER BY [Name])) + ' As [Name]',
        @PivCols = COALESCE(@PivCols + ',','') + QUOTENAME(ROW_NUMBER() OVER (ORDER BY [Name]))
FROM    myTable 
WHERE   [Id] = @Id


--Build the dynamic sql 
SET     @Sql = 'SELECT [Id], ' + @SelCols + ' 
                FROM (  SELECT  [Id], [Name], ROW_NUMBER() OVER (PARTITION BY [Id] ORDER BY [Name]) Rn
                        FROM    myTable 
                        WHERE   [Id] = @Id) mt
                PIVOT (
                    MAX([Name])
                    FOR Rn IN (' + @PivCols + ')) p'

--Execute the dynamic sql passing in the @Id parameter
EXECUTE sp_executesql @Sql, N'@Id VARCHAR(8)', @Id = @Id

--@Id = '1Bravo` result
--Id       Name  Name
---------- ----- -----
--1Bravo   John  Smith

--@Id = '2Charlie` result
--Id       Name  Name  Name
---------- ----- ----- -----
--2Charlie Billy Bobby Dave

答案 1 :(得分:-1)

您应首先限制您的最大名称数量(我在查询中设置10个名称),然后您可以转动它。

我添加了一个列,其中包含行(cnt)中的名称总数,以便于循环或检查,而无需查找第一个空名称。

;with
YourTable as (
    select * 
    from ( 
    values 
        ('1Bravo',      'John'),
        ('1Bravo',      'Smith'),
        ('2Charlie',    'Dave'),
        ('2Charlie',    'Billy')
    ) t (Id, Name)
),
n as (
    select id, count(distinct name) cnt 
    from YourTable
    group by id
),
x as (
    select *, ROW_NUMBER() over (partition by id order by name) idx
    from YourTable
)
select n.cnt, p.*
from x 
pivot (min(name) for idx in ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10])) p
inner join n on n.Id = p.Id

然后,您可以过滤所需的ID

where n.id like '%bravo%'

我希望这会有所帮助