计算值的出现次数并将其打印出来

时间:2013-10-17 14:24:37

标签: php mysql count distinct

我知道在阅读了很多答案之前已经涵盖了这个问题,他们都告诉我如何编写SQL而不是如何打印结果。

我的困境是我有一个带有付款方式字段的订单表,看起来像这样

OrderID     OrderNumber     PaymentMethod
 1234         a1b2c3          PayPal
 1235         a1b2c4          Account
 1236         a1b2c5          Account
 1237         a1b2c6          PayPal
 1238         a1b2c7          Account
 1239         a1b2c8          PayPal
 1230         a1b2c9          PayPal

我需要打印出类似

的内容

PayPal付款次数:4

帐户付款次数:3

我试过用这个答案

MySQL: Count occurrences of distinct values

我有这个代码

SELECT PaymentMethod,COUNT(*) as Payment FROM tablename GROUP BY PaymentMethod ORDER BY Payment DESC;

但如何打印出来?

2 个答案:

答案 0 :(得分:1)

$returned = mysqli_query("SELECT PaymentMethod,COUNT(distinct PaymentMethod) as Payment FROM tablename GROUP BY PaymentMethod ORDER BY Payment DESC;");
while($data = mysqli_fetch_assoc($returned)){
    echo "Number of " . $data['PaymentMethod'] . ": " . $data[0] . "<br>";
}

答案 1 :(得分:0)

您应该将数据表示留给VIEW。

话虽如此,这就是你如何使用纯粹的MySQL提取以这种方式格式化的数据:

SELECT concat('Number of ', paymentmethod ,' payments: ', count(*)) RESULT FROM t
GROUP BY paymentmethod
ORDER BY paymentmethod DESC

这导致:

|                        RESULT |
|-------------------------------|
|  Number of PayPal payments: 4 |
| Number of Account payments: 3 |

小提琴here