2012-03-30 50 views
0

我有以下表(簡體):獲取個人和總工作小時

user_id date   hours 
1   2012-03-01  5 
2   2012-03-01  8 
3   2012-03-01  6 
1   2012-03-02  3 
3   2012-03-02  7 

我要的是得到的小時和工作對於一個給定的用戶ID(例如1。 ),並且無論在單個查詢中哪個用戶(對於給定的時間段)都工作的總小時數。

所以對於USER_ID = 1,和時間:2012-03-01 - 2012-03-02查詢應該返回:自己= 8,總= 29

我可以做兩個單獨的查詢,但不是在一個單獨的查詢。

回答

5

使用CASE

SELECT SUM(
    CASE user_id 
     WHEN 1 THEN hours 
     ELSE 0 
    END) as Own, 
SUM(hours) as Total 
FROM HoursWorked 
WHERE date BETWEEN '2012-03-01' AND '2012-03-02'; 
+0

U很快@Diego ... :) – Teja 2012-03-30 17:37:39

0

迭戈的回答雖然程序是一個偉大的方式來獲得你正在尋找的答案。當然,對於你的日期範圍,你需要在'startdate'和'enddate'之間添加一個WHERE日期。這些日期需要採用mysql識別的格式,通常爲'yyyy-mm-dd'

另一種解決方案不會讓您在一行中得到結果,但在結果集中將執行UNION

SELECT user_id, SUM(hours) as hours FROM table WHERE date BETWEEN 'startdate' AND 'enddate' WHERE user_id = 3 
UNION 
SELECT null as user_id, SUM(hours) as hours FROM table WHERE date BETWEEN 'startdate' AND 'enddate' 
1

我覺得我有一些使用下面的架構的作品:

CREATE TABLE hoursWorked 
    (
    id int, 
    date date, 
    hours int 
    ); 

INSERT INTO hoursWorked 
(id, date, hours) 
VALUES 
('1','2012-03-01','5'), 
('2','2012-03-01','8'), 
('3','2012-03-01','6'), 
('1','2012-03-02','3'), 
('3','2012-03-02','7'); 

而這個查詢:

select parent.id, parent.date, parent.hours, (select sum(hours) 
         from hoursWorked child 
         where child.id = parent.id) as totalHours 
from hoursWorked parent 

我能夠得到這些結果:

ID DATE       HOURS TOTALHOURS 
1 March, 01 2012 00:00:00-0800 5 8 
2 March, 01 2012 00:00:00-0800 8 8 
3 March, 01 2012 00:00:00-0800 6 13 
1 March, 02 2012 00:00:00-0800 3 8 
3 March, 02 2012 00:00:00-0800 7 13