如何“SUM”唯一列值和按日期过滤

时间:2015-09-09 10:06:01

标签: php mysql

INPUT

+------------+----------+-----------+-------+-------------+
|     cardNo | userName | tablename | hours |    date     |
+------------+----------+-----------+-------+-------------+
|          1 | a        | a         |    12 | 12-06-2015  |
|          1 | a        | a         |     5 | 11-06-2015  |
|          2 | b        | b         |     3 | 15-06-2015  |
|          1 | a        | a         |     8 | 12-06-2015  |
|          2 | b        | b         |     3 | 21-06-2015  |
|          1 | a        | a         |    12 | 14-06-2015  |
|          2 | b        | b         |    10 | 8-06-2015   |
+------------+----------+-----------+-------+-------------+

cardNo是独一无二的。我需要显示每张卡的所有详细信息和总小时数,例如:

渴望输出

+--------+----------+-----------+-------------+
| cardNo | userName | tablename | totalhours  |
+--------+----------+-----------+-------------+
|      1 | a        | a         |         37  |
|      2 | b        | b         |         16  |
+--------+----------+-----------+-------------+

我的查询

SELECT cardNo,sum(hours) 
FROM yourtable
GROUP BY cardNo;

但是我需要totalHours> = 20是'N'。

SELECT cardNo,sum(hours) 
FROM yourtable where totalHours>=20
GROUP BY cardNo;

我无法得到正确的答案。如果我指定totalHours> = 1,它会给出正确答案我能做什么。而且我还需要为该查询提供php获取代码..

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

使用HAVING子句:

SELECT cardNo,sum(hours) as TotalHours
FROM yourtable
WHERE date  BETWEEN fromdate AND todate
GROUP BY cardNo
HAVING sum(hours) >=20

使用WHERE子句,您可以获得这些日期之间每张卡片的总小时数。