2015-09-09 60 views
0

INPUT如何 「SUM」 唯一的列值,並篩選按日期

+------------+----------+-----------+-------+-------------+ 
|  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 | 
+--------+----------+-----------+-------------+ 

MY QUERY

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提取代碼的查詢..

任何人都可以幫忙嗎?

回答

3

使用HAVING條款:

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

使用WHERE子句,你可以得到總小時數每cardNo這些日期之間。

+0

我需要檢查日期。日期> ='N'和日期<='N' –

+0

@BalaMurugan:更新了我的答案。現在就試試。 –

+0

非常感謝你,這是完美的工作...憤怒的公牛 –