X基于一列的行数

时间:2013-11-29 11:55:18

标签: sql sql-server

我被要求将X行显示为与结果相符的行。例如: -

数据

 Tency Number| ClientNo  |  Name |  DOB       | Prim Client |  Rent
 10001          20          Joe    01/10/1900    Y            100 
 10001          21          bob    01/10/1901    N            100 
 10001          26          jim    01/10/1902    n            100 

用户想要的格式是

Tency Number | ClientNo | Name | DOB        | Prim Client | Rent | Client2 | DOB 2|
10001          20          Joe   01/10/1900      Y           100 |   Bob   01/10/1901 | Jim | 01/10/1902

我们没有预定数量的客户链接到Tenacy Number。我迷失了用于实现这一目标的东西。没有任何东西可以转动表格,我使用STUFF将所有客户端链接到行上的一列(但他们不希望这样)。

这可能吗?如果是这样,我将如何实现它?

谢谢!

1 个答案:

答案 0 :(得分:3)

您需要的SQL将是:

SELECT  TencyNumber, 
        ClientNo = MIN(CASE WHEN RowNum = 1 THEN ClientNo END),
        Client1 = MAX(CASE WHEN RowNum = 1 THEN Name END),
        DOB1 = MAX(CASE WHEN RowNum = 1 THEN DOB END),
        Client2 = MAX(CASE WHEN RowNum = 2 THEN Name END),
        DOB2 = MAX(CASE WHEN RowNum = 2 THEN DOB END),
        Client3 = MAX(CASE WHEN RowNum = 3 THEN Name END),
        DOB3 = MAX(CASE WHEN RowNum = 3 THEN DOB END)
FROM (  SELECT  TencyNumber, 
                ClientNo,
                Name,
                DOB, 
                PrimClient,
                Rent,
                RowNum = ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name)
        FROM    T
    ) c
GROUP BY TencyNumber;

但是由于您拥有未知数量的客户端,因此您需要动态构建SQL:

DECLARE @SQL NVARCHAR(MAX) = '';
SELECT   @SQL = @SQL + 
                    ',Client' + RowNum + ' = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN Name END)
                    ,DOB' + RowNum + ' = MAX(CASE WHEN RowNum = ' + RowNum + ' THEN DOB END)'
FROM    (   SELECT  RowNum = CAST(ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name) AS VARCHAR(10))
            FROM    T
        ) c;

SET @SQL = 'SELECT TencyNumber, ClientNo = MIN(CASE WHEN RowNum = 1 THEN ClientNo END) ' + @SQL + '
            FROM (  SELECT  TencyNumber, 
                            ClientNo,
                            Name,
                            DOB, 
                            PrimClient,
                            Rent,
                            RowNum = ROW_NUMBER() OVER(PARTITION BY TencyNumber ORDER BY Name)
                    FROM    T
                ) c
            GROUP BY TencyNumber;';
EXECUTE SP_EXECUTESQL @SQL;

<强> Example on SQL Fiddle