1
INSERT INTO tablex(Id, Name, Team, Joined) VALUES

(1, 'Mr. A', 'X', '2011-02-22'),

(2, 'Mr. B', 'Y', '2011-02-11'),

(3, 'Ms. C', 'X', '2011-02-10'),

(4, 'Mr. D', 'Y', '2011-01-12'),

(5, 'Ms. E', 'X', '2011-01-06'),

(6, 'Mr. F', 'Y', '2011-05-02');

(7, 'Mr. H', 'X', '2011-02-01');

output required is:

Month   | Team | TotalMembers | Percentage

 01/2011  | X    |   1          |   50

 01/2011  | Y    |   1          |   50

 02/2011  | X    |   2          |   75

 02/2011  | Y    |   1          |   25

 05/2011  | X    |   0          |   0

 05/2011  | Y    |   1          |   100

Please help me to do the above. Mostly preferred in MySQL (GROUP BY Team, DATE_FORMAT(Joined, '%m/%Y')). but can use PHP.

Thanks in advance

2
  • 1
    Ca you explain the Percentage column? If it is, as I suppose it is, the ratio of members joined in one team to all members joined that month then rows 3 and 4 are not correct, should stay 66.6 and 33.3 ? Commented Oct 12, 2011 at 11:16
  • Is it necessary to have a 0 record for 5/11, team X? Won't that cause a lot of 0 records to appear in the output if you have another team, say team Z? Commented Oct 12, 2011 at 14:53

1 Answer 1

2

There can be more elegant solutions but this one should work:

SELECT DATE_FORMAT( Joined, '%m/%Y' ) AS
    MONTH , team, (
    count( id ) / (
    SELECT count( * )
    FROM tablex
    WHERE DATE_FORMAT( Joined, '%m/%Y' ) = DATE_FORMAT( tx.Joined, '%m/%Y' )
    GROUP BY DATE_FORMAT( Joined, '%m/%Y' ) ) *100
    ) AS percentage
    FROM `tablex` AS tx
    GROUP BY DATE_FORMAT( Joined, '%m/%Y' ) , team
Sign up to request clarification or add additional context in comments.

4 Comments

+1 Excellent answer! One minor issue though -- it doesn't include the 5/11 record for X that has 0 team members: sqlize.com/164lD5bwbw
But what if you have a team Z on 06/11, will you get a lot of records with 0's for X and Y? If you want that, you're looking at a whole different solution.First retreive all possible teams, then query the db for all the months. Then for each month calculate the total members and percentage and add 0 for non-existing teams. You could probably do it in one query but performance will be a disaster
I agree with you. I'm just noting the discrepency between your solution and what the OP posted as the "required output". I would take that concern up with the OP.
Thanks Nin! It was very useful. In continuation to this I've posted other query please have a look at this link. link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.