我编写了以下查询以返回有关在X时间内进行的购买的一些统计信息。但由于某种原因,每个“COUNT”列返回总行数。我是否错误地组织了查询?
SELECT COUNT(*) as countTotal, SUM(`cost`) as cost, COUNT(`paymentType` = 'credit') as count_credit, COUNT(`paymentType` = 'cash') as count_cash
FROM `purchase` WHERE `date` >= '2011-5-4'
更新
我刚决定使用子查询。这就是我最终的目标。
SELECT
COUNT(*) as countTotal,
SUM(`cost`) as cost,
(SELECT COUNT(*) FROM `purchase` WHERE `paymentType` = 'credit') as count_credit,
(SELECT COUNT(*) FROM `purchase` WHERE `paymentType` = 'cash') as count_cash
FROM `purchase` WHERE `date` >= '2011-5-4'
UPDATE2
使用的ypercubes回答如下。
答案 0 :(得分:4)
count确实返回查询的域或组的行数。看起来您需要按PaymentType进行分组才能实现您的目标。
SELECT PaymentType, COUNT(*) as countTotal, SUM(`cost`) as cost,
FROM `purchase`
WHERE `date` >= '2011-5-4'
Group by PaymentType
这是一个参考 http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
答案 1 :(得分:2)
看起来不正确,但将COUNT()
更改为SUM()
可以正常工作:
SELECT COUNT(*) AS countTotal
, SUM(cost) AS cost
, SUM(paymentType = 'credit') AS count_credit --- SUM does counting here
, SUM(paymentType = 'cash') AS count_cash --- and here
FROM purchase
WHERE `date` >= '2011-05-04'
解释:True == 1
和False == 0
用于MySQL。
答案 2 :(得分:0)
在WHERE子句
之后需要一个GROUP BY子句