如何在表上形成mysql查询以按名为“类型”的列和另一列的计数进行分组

时间:2019-11-27 13:09:16

标签: mysql mysql-5.7

我有一个表,该表的列名为'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>

因此,第一列与“类型”列不同。第二和第三列将来自“结果”列。如果Type1值为's',则将Count添加到S Count中,否则将F计数添加至S Count。

如何形成如下查询,

select type,result,count(id) from test_table group by type,result;

对于每种类型,此结果将作为2个单独的行给出结果,但我想像上面给出的预期结果那样。

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT
    Type,
    SUM(Result = 's') AS s_count,
    SUM(Result = 'f') AS f_count
FROM yourTable
GROUP BY
    Type;

screen capture of demo below

Demo