Selecting and displaying the count of rows with the same value in a table

大憨熊 提交于 2019-12-25 07:48:46

问题


Basically this is a survey system and I want to count the Yes's and No's from my results table which has

  | q1  | q2  | q3 | q4 | q5 | q6  | q7 | q8  | q9  | q10 |

  | Yes | Yes | No | No | No | Yes | No | Yes | Yes | No  |

  | No | Yes | No | Yes | Yes | Yes | No | No  | Yes | No |

  | Yes | Yes | No | No | No | Yes | No | Yes | Yes | No  |

  | No | Yes | No | Yes | Yes | Yes | No | No  | Yes | No |

For example I want my result to be q1 = 2 No's 2 Yes and q2 = 4 yes 0 No's and so on Then after that I was hoping to display it in a simple table but I'm still clueless about the query


<body>

<form method="POST">


    <table border="1">

            <th>Answered Yes</th>
            <th>Answered No</th>
        </tr>

        <?php
        include("testdb.php");
        $result= mysqli_query($con, "SELECT * FROM results");

        if($result){

        ?>


    </table>

</body>

回答1:


Just use boolean expressions:

select ((q1 = 'Yes') + (q2 = 'Yes') + . . .  + (q10 = 'Yes')) as numYes

MySQL treats a conditional expression as a number in a numeric context, with 1 for true and 0 for false.




回答2:


In MySQL (only) true is 1 and false is 0, so summing a condition counts how many times it's true:

select
    sum((q1 = 'Yes') + (q2 = 'Yes') + ... etc) yeses,
    sum((q1 = 'No') + (q2 = 'No') + ... etc) nod
from mytable


来源:https://stackoverflow.com/questions/41538841/selecting-and-displaying-the-count-of-rows-with-the-same-value-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!