如何根据mysql中的条件计算数据? [英] how to count datas according to condition in mysql?

查看:158
本文介绍了如何根据mysql中的条件计算数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨朋友

我想描述我的问题有一个数据库表,这些表有一些我想要数据的列......





id上课ZK

1 x 0 0

2 x 0 0

3 x 2 1

4 x 2 1



只有当Z列为零时我才算数,所以这个结果将是2

从表中选择count(x),其中z = 0,此结果有2



但是当K列值为1时,我将添加2个数据,因此结果将是4



这里有一个条件通常sql会计算如果z = 0所以结果2

如果k = 1 sql count all all this so result将是4



条件计数

应该如何将mysql查询字符串?

非常感谢。

hi friends
I want to describe my problem there is a database table these table has some column I wanto to count datas...


id lesson Z K
1 x 0 0
2 x 0 0
3 x 2 1
4 x 2 1

only I will count when Z column has zero so this result will be 2
select count(x) from table where z=0 this result has 2

but when K column value is 1 I will add 2 datas so result will be 4

there is a condition here normally sql will count if z=0 so result 2
if k=1 sql count all of them so result will be 4

conditional count
how should be mysql query string?
thanks a lot.

推荐答案

它应该有效:

It should works:
SELECT SUM(CountMyCol) AS SumOfZK
FROM(
    (SELECT COUNT(x) CountMyCol
    FROM MyTable
    WHERE z=0)
    UNION ALL
    (SELECT COUNT(x) CountMyCol
    FROM MyTable
    WHERE k=1))





更多:

http://dev.mysql.com/doc/refman/5.0/en/union.html [ ^ ]

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html [ ^ ]


这篇关于如何根据mysql中的条件计算数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆