行到列转换Sql查询SQL SERVER

时间:2014-05-10 05:33:54

标签: sql-server

我有一个表名#Table1(见附件)我想跟进(见附件)

enter image description here

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT FormatType,
       ISNULL(COUNT(CASE WHEN Result='True' THEN '1' END),0) AS [True],
       ISNULL(COUNT(CASE WHEN Result='False' THEN '1' END),0) AS [False],
       ISNULL(COUNT(CASE WHEN Result='Blank' THEN '1' END),0) AS [Blank],
       ISNULL(COUNT(1),0) AS [Total]
FROM Table1
GROUP BY FormatType
ORDER BY FormatType DESC

<强>解释

此查询将根据每个案例的计数和总数选择FormatTypeISNULL用于将NULL值替换为0(如果FALSE中为ASP)。

结果:

FORMATTYPE  TRUE    FALSE   BLANK   TOTAL
PSP         1       2       1       4
ASP         1       0       2       3

请参阅SQL Fiddle中的结果。

答案 1 :(得分:4)

@Raging Bull的回答是正确的。这是使用PIVOT的版本

SELECT FormatType, [True], [False], [Blank], [True] + [False] + [Blank] AS Total
FROM
(
    SELECT FormatType, Result
    FROM Table1
) AS SourceTable
PIVOT
(
    COUNT(Result)
    FOR Result IN ([True], [False], [Blank])
) AS PivotTable

它产生完全相同的结果。

请参阅SQL Fiddle

中的结果