我有一个表名#Table1(见附件)我想跟进(见附件)
答案 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
<强>解释强>
此查询将根据每个案例的计数和总数选择FormatType
。 ISNULL
用于将NULL
值替换为0
(如果FALSE
中为ASP
)。
结果:
FORMATTYPE TRUE FALSE BLANK TOTAL
PSP 1 2 1 4
ASP 1 0 2 3
请参阅SQL Fiddle中的结果。
答案 1 :(得分:4)
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
中的结果