如何在 table 上形成 mysql 查询以按名为 'type' 的列和另一列的计数进行分组
How to form mysql query on a table to group by a column named 'type' and count of another column
我有 table,其中有一列名为 'Type',另一列 'Result' 的值为 's' 和 'f'。
<table border="1" width="100%">
<tr>
<td >Type</td>
<td >Result</td>
</tr>
<tr>
<td>t1</td>
<td>s</td>
<tr>
</tr>
<td>t2</td><td>s</td>
<tr>
</tr>
<td>t1</td><td>f</td>
<tr>
</tr>
<td>t1</td><td>f</td>
</tr>
</table>
我想要
这样的结果
<table border="1" width="100%">
<tr>
<td >Type</td>
<td >S Count</td>
<td >F Count</td>
</tr>
<tr>
<td>t1</td>
<td>1</td>
<td>2</td>
<tr>
</tr>
<td>t2</td>
<td>1</td>
<td>0</td>
<tr>
</table>
所以第一列与 'type' 列不同。第二和第三列将来自 'Result' 列。如果 Type1 值为 's',则计数将添加到 S 计数,否则将添加到 F 计数。
如何形成如下查询,
select type,result,count(id) from test_table group by type,result;
这将给出每种类型的 2 行单独的结果,但我想要上面给出的预期结果。
使用条件聚合:
SELECT
Type,
SUM(Result = 's') AS s_count,
SUM(Result = 'f') AS f_count
FROM yourTable
GROUP BY
Type;
我有 table,其中有一列名为 'Type',另一列 'Result' 的值为 's' 和 'f'。
<table border="1" width="100%">
<tr>
<td >Type</td>
<td >Result</td>
</tr>
<tr>
<td>t1</td>
<td>s</td>
<tr>
</tr>
<td>t2</td><td>s</td>
<tr>
</tr>
<td>t1</td><td>f</td>
<tr>
</tr>
<td>t1</td><td>f</td>
</tr>
</table>
我想要
这样的结果<table border="1" width="100%">
<tr>
<td >Type</td>
<td >S Count</td>
<td >F Count</td>
</tr>
<tr>
<td>t1</td>
<td>1</td>
<td>2</td>
<tr>
</tr>
<td>t2</td>
<td>1</td>
<td>0</td>
<tr>
</table>
所以第一列与 'type' 列不同。第二和第三列将来自 'Result' 列。如果 Type1 值为 's',则计数将添加到 S 计数,否则将添加到 F 计数。
如何形成如下查询,
select type,result,count(id) from test_table group by type,result;
这将给出每种类型的 2 行单独的结果,但我想要上面给出的预期结果。
使用条件聚合:
SELECT
Type,
SUM(Result = 's') AS s_count,
SUM(Result = 'f') AS f_count
FROM yourTable
GROUP BY
Type;