开发者

mySQL Group By question

Hi how do i gr开发者_Python百科oup 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?


Use GROUP_CONCAT():

SELECT Date, Day, Duration group_concat(IdStaff + '(' + Duration + ')' SEPARATOR ',')
from yourtable
group by Date, Day, Duration


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 :

mySQL Group By question

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜