我如何知道mysqli选择中值出现的次数

时间:2016-07-21 18:48:48

标签: php mysqli

请问我如何知道大卫投票数为2的次数

Name  | Vote
-------------
|Gabri| 2
|David| 2
|Janny| 3
|David| 1
|David| 2
|Fally| 3

2 个答案:

答案 0 :(得分:0)

WITH CTE AS (
    SELECT
        COUNT(*) AS NumberOfOrder
        , SUM(Approved) AS NumberOfApproved
        , SUM(Denied) AS NumberOfDenied
        , SUM(IIF(Approved=1 AND Denied=1,1,0)) AS NumberOfError
        , ID
    FROM
        TestTable T1
    GROUP BY
        T1.ID
)
SELECT
    T2.*
    , CASE
        WHEN CTE.NumberOfError > 0 THEN 'Error'
        WHEN CTE.NumberOfApproved=CTE.NumberOfOrder THEN 'Approved'
        WHEN CTE.NumberOfDenied=CTE.NumberOfOrder THEN 'Denied'
        WHEN CTE.NumberOfApproved>0 OR CTE.NumberOfDenied > 0 THEN 'Partially Approved'
        ELSE 'Pending Approval'
    END AS Approval_Status
FROM
    TestTable T2
    JOIN CTE ON T2.ID=CTE.ID

输出

$sql = "SELECT count(*) from table_name WHERE Name= 'David' and Vote=2";
$result = mysqli_query($con, $sql);
$fetch = mysqli_fetch_assoc($result);
echo "<pre>";
print_r($fetch);
echo "<pre>";

只需Array ( [count(*)] => 4 )

即可获得所需的值

答案 1 :(得分:0)

select Name , count(Name) where Name = 'David' group by Name having count(Name) =2