SQL-将所有用户合并在一个表中

时间:2019-01-30 17:00:19

标签: sql sql-server unpivot

表:流行

UserName   FriendName
--------   ---------- 
John       Sarah
Philip     Ursula
John       Marry
John       Jeremy
Philip     Brock
Khan       Lemy

我想要查询列表;

John       Philip       Khan
--------   ----------   --------
Sarah      Ursula       Lemy
Marry      Brock        -NULL-
Jeremy     -NULL-       -NULL-

我有100多个用户名...帮助我列出SQL查询(MSSQL)

3 个答案:

答案 0 :(得分:5)

如果您有“ 100+个用户名”,则希望它是动态的,这样您就不必为每个用户名键入特定的CASE语句。

此外,您也不需要每次将新的UserName添加到表中时都更新脚本。

以下脚本将动态检索所有不同的用户名,并为他们创建一列,并为所有朋友提供行。

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

    SET @cols = STUFF((SELECT distinct ',MAX(CASE WHEN UserName = ''' 
                        + p.UserName + ''' THEN FriendName END) AS ' 
                        + QUOTENAME(p.UserName) FROM Popular p
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')

    SET @query = 'SELECT ' + @cols + ' FROM 
                (SELECT UserName, FriendName
                    ,ROW_NUMBER() OVER (PARTITION BY UserName ORDER BY FriendName) AS RowNum
                    FROM Popular GROUP BY USERNAME, FRIENDNAME
                ) x
                GROUP BY RowNum'

    EXECUTE(@query);

我从上面的输出如下所示;

╔════════╦══════╦════════╗
║  John  ║ Khan ║ Philip ║
╠════════╬══════╬════════╣
║ Jeremy ║ Lemy ║ Brock  ║
║ Marry  ║ NULL ║ Ursula ║
║ Sarah  ║ NULL ║ NULL   ║
╚════════╩══════╩════════╝

您应该能够针对整个表运行此操作,并获得所有可能的UserName的结果,而不必键入单个CASE语句。

对于任何想要测试的人,这里是测试表和数据脚本;

    IF EXISTS ( SELECT *
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_NAME = 'Popular'
                AND TABLE_SCHEMA = 'dbo'
                AND TABLE_TYPE = 'TABLE')
    DROP TABLE [dbo].[Popular];
    GO

    CREATE TABLE [dbo].[Popular]
    (
    UserName VARCHAR(20),
    FriendName VARCHAR(20)
    );
    GO

    INSERT INTO [dbo].[Popular] (UserName,FriendName) VALUES
    ('John','Sarah'),
    ('Philip','Ursula'),
    ('John','Marry'),
    ('John','Jeremy'),
    ('Philip','Brock'),
    ('Khan','Lemy');

答案 1 :(得分:2)

用例何时

QCombobox

编辑:您需要select max(case when UserName='John' then fieldname end) as john, max(case when UserName='Philip' then fieldname end) as Philip, max(case when UserName='Khan' then fieldname end) as Khan from table_name

row_number()

答案 2 :(得分:0)

我想你可以用支点 https://docs.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017

-- Pivot table with one row and five columns  
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,   
[0], [1], [2], [3], [4]  
FROM  
(SELECT DaysToManufacture, StandardCost   
FROM Production.Product) AS SourceTable  
PIVOT  
(  
AVG(StandardCost)  
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])  
) AS PivotTable;  

那是代码:

if OBJECT_ID('userName') is not null drop table userName;

create table userName (fiiduserName int identity(1,1), fcName varchar(20), 
fcFrienlyName varchar(20));

insert into userName(fcName, fcFrienlyName)values ('John', 'Sarah');
insert into userName(fcName, fcFrienlyName)values ('Philip', 'Ursula');
insert into userName(fcName, fcFrienlyName)values ('John', 'Marry');
insert into userName(fcName, fcFrienlyName)values ('John', 'Jeremy');
insert into userName(fcName, fcFrienlyName)values ('Philip', 'Brock');
insert into userName(fcName, fcFrienlyName)values ('Khan', 'Lemy');

declare @Nombres varchar(max);
declare @select varchar(max);

select @Nombres = COALESCE(@Nombres + ',', '') + '[' + fcName + ']'
from userName
group by fcName;

select @select  = 'SELECT fiiduserName, ' +  @Nombres + '
FROM  
(SELECT fiiduserName, fcName, fcFrienlyName
    FROM userName) AS SourceTable  
PIVOT  
(  
MIN(fcFrienlyName)  
FOR fcName IN (' + @Nombres + ')
) AS PivotTable; ' 

exec (@select);

drop table userName;