Group some fields

Discussion in 'MySQL' started by Atabek, May 16, 2011.

  1. #1
    Hello dear friend.

    Another question, which i need your help

    table1:

    | id | name | works | hours |
    ----------------------------
    | 1 | bob | wrk1 | 1 |
    | 2 | bob | wrk2 | 3 |
    | 3 | bob | wrk3 | 2 |
    | 4 | bob | wrk4 | 3 |
    | 5 | tom | wrk1 | 2 |
    | 6 | tom | wrk4 | 1 |
    | 7 | tom | wrk3 | 3 |
    | 8 | ann | wrk2 | 1 |
    | 9 | ann | wrk3 | 3 |
    |... | ... | ... | ... |

    Here `wrkx` used one time in each name, e.g. `bob` can `wrk1` only one time or none time.

    Can I group by name and get such kind of results:

    | id | name | wrk1 | wrk2 | wrk3 | wrk4 | ... | wrkN | - came from table1.works
    ----------------------------------------------------
    |1 | bob | 1 | 3 | 2 | 3 | null| null |
    |2 | tom | 2 | null | 3 | 1 | null| null |
    |3 | ann | null | 1 | 3 | null | null| null |

    There is `wrkN` - N < 30

    Pardon me my english.

    Thanks.
     
    Atabek, May 16, 2011 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    What you're suggesting is equivalent to a vertical lookup or horizontal aggregation. You need to do it on the application level. It's not really practical to do it within MySQL unless you use some really complicated querying, if it is at all possible.
     
    jestep, May 17, 2011 IP
  3. plog

    plog Peon

    Messages:
    298
    Likes Received:
    11
    Best Answers:
    1
    Trophy Points:
    0
    #3
    It easy, but tedious. Essentially you create an aggragate query that sums a bunch of conditional fields like this:

    SELECT name, SUM(IF(works='wrk1', hours, 0)) AS wrk1, SUM(IF(works='wrk2', hours, 0)) AS wrk2....
    FROM table1 GROUP BY name;
    
    PHP:
    Just keep adding: SUM(IF(works='wrkn', hours, 0)) AS wrkn
    to account for every wrkn possible.
     
    plog, May 17, 2011 IP
  4. Atabek

    Atabek Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I think so, thank You.
     
    Atabek, May 17, 2011 IP
  5. Atabek

    Atabek Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thank You,
    another question, in this case e.g. tom has no wrk2 , so result must be null (not integer). How can i get such result
     
    Atabek, May 17, 2011 IP
  6. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #6
    Just replace 0 with NULL.
     
    jestep, May 17, 2011 IP
  7. Atabek

    Atabek Peon

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Thank you.
     
    Atabek, May 21, 2011 IP