tags:

views:

47

answers:

2

Hi how do i group this data:

**Date** **Day** **DURATION** **IDSTAFF**

21-09-2010 Sun      AM           1   
22-09-2010 Mon      AM           1  
21-09-2010 Sun      PM           2  
22-09-2010 Mon      PM           2  

So it will become like this?

**Date** **Day** **DURATION** **IDSTAFF**

21-09-2010 Sun      AM           1 (am),2 (pm)   
22-09-2010 Mon      AM           1 (am),2  (pm)

Using sql group by will only show one id staff. Can sql queries solve this or need to use php?

+3  A: 

Use GROUP_CONCAT():

SELECT Date, Day, Duration group_concat(IdStaff + '(' + Duration + ')' SEPARATOR ',')
from yourtable
group by Date, Day, Duration
Michael Pakhantsov
the (IdStaff + '(' + Duration + ')' is not working. For example IdStaff is 4 and Duration is 1, the output will be 5 not 4(1). So if the IdStaff is 4 and Duration is AM, the output is 4. How to solve this?
cyberfly
+1  A: 

The correct answer to this problem:

SELECT DATE, DAY, GROUP_CONCAT(IDSTAFF, ' (' , PERIOD , ')' SEPARATOR ', ') AS PERSONNAME FROM LEAVERECORD GROUP BY DATE

If you want to get the name for each idstaff, use the subquery in the group_concat and concat the firstname and lastname. Example:

SELECT DATE, DAY, PERIOD, GROUP_CONCAT((SELECT CONCAT(FIRSTNAME,' ',LASTNAME) from STAFF where STAFF.IDSTAFFTABLE=IDSTAFF), ' (' , PERIOD , ')' SEPARATOR ', ') AS PERSONNAME FROM LEAVERECORD GROUP BY DATE

The result :

alt text

cyberfly