如何格式化选择查询输出

时间:2016-05-25 06:43:59

标签: sql sql-server sql-server-2008

我在下面有这样的表格,

Type             Model       Year    
121232323        Test1       2000
121232323        Test2       2001

我想要输出如下,如何为此编写查询。?

121232323       Test1      Test2
                2000       2001

3 个答案:

答案 0 :(得分:2)

使用Simple Pivot我们可以实现

DECLARE @Table1 TABLE 
    ( Type  int,  Model  varchar(5),  Year  int)
;

INSERT INTO @Table1
    ( Type ,  Model ,  Year )
VALUES
    (121232323, 'Test1', 2000),
    (121232323, 'Test2', 2001)
;


select Type,[Test1],[Test2] from @Table1
PIVOT (MAX(YEAR) FOR MODEL IN ([Test1],[Test2]))PVT

答案 1 :(得分:2)

我不了解Originalnr,但如果您的测试数量有限,则可以使用条件聚合执行此操作:

SELECT t.Type,
       MAX(CASE WHEN t.Model = 'Test1' THEN t.Year END) as Test1,
       MAX(CASE WHEN t.Model = 'Test2' THEN t.Year END) as Test2
FROM YourTable t
GROUP BY t.Type

答案 2 :(得分:2)

PIVOT之外的另一种方法是使用条件聚合:

SELECT
    Type,
    Test1 = MAX(CASE WHEN Model = 'Test1' THEN [year] END),
    Test2 = MAX(CASE WHEN Model = 'Test2' THEN [year] END)
FROM tbl
GROUP BY Type

如果你有Model个无限数量,你可以使用动态交叉表:

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql =
'SELECT
    Type' + CHAR(10) +
(SELECT DISTINCT
'   , MAX(CASE WHEN Model =''' + Model +  ''' THEN [year] END) AS ' + QUOTENAME(Model) + CHAR(10)
FROM tbl
FOR XML PATH('')
) +
'FROM tbl
GROUP BY Type;';

PRINT(@sql);
EXEC(@sql);

ONLINE DEMO