I am working on project where I have reports that have three states its "checked","inprocess" and "completed"
Got two tables!
tbl_tracking - for keeping track of reports
report_id usr_id date status
----------------------------------------------
0000 abc 2014/04/05 checked
0001 abc 2014/04/05 checked
0000 abc 2014/04/05 inprocess
0001 abc 2014/04/05 completed
0002 abc 2014/04/06 completed
0004 xyz 2014/04/05 checked
0005 xyz 2014/04/06 checked
tbl_timestatus- for keeping track of time employees have worked on reports
usr_id date time_worked (hrs)
----------------------------------------------
abc 2014/04/05 6
abc 2014/04/06 5
Now I want to create a view to always display up-to-date status of everything so I code this
CREATE VIEW VW_STATUS AS
SELECT tb1.usr_id, tb1.date,
COUNT(CASE tb1.status WHEN 'checked' THEN 1 ELSE NULL END) AS checkedcount,
COUNT(CASE tb1.status WHEN 'inprocess' THEN 1 ELSE NULL END) AS inprocesscount,
COUNT(CASE tb1.status WHEN 'completed' THEN 1 ELSE NULL END) AS compltedcount,
CASE WHEN (tb1.usr_id=tb2.usr_id AND tb1.date=tb2.date) THEN tb2.time_worked ELSE NULL END AS timeworked
FROM tbl_tracking tb1, tbl_timestatus tb2
GROUP BY tb1.usr_id, tb1.date;
Expected Output:
usr_id date checkedcount inprocesscount completedcount timeworked
---------------------------------------------------------------------------------------
abc 2014/04/05 2 1 1 6
abc 2014/04/06 0 0 1 5
xyz 2014/04/05 1 0 0 NULL
xyz 2014/04/06 1 0 0 NULL
Actual Output:
usr_id date checkedcount inprocesscount completedcount timeworked
---------------------------------------------------------------------------------------
abc 2014/04/05 4 2 2 6
abc 2014/04/06 0 0 2 5
xyz 2014/04/05 2 0 0 NULL
xyz 2014/04/06 2 0 0 NULL
While the "timeworked" values remain correct, the count(*)'s add themselves twice!! There is some problem with join! Need help on same..