How can I achieve pivot table output in MySQL?

141 views Asked by At

If I have a MySQL table looking something like this:

A sample data

How to write a mysql query to get output like this:

userid        total_entries      products_sold
------------------------------------------------------------------
204           1011               1500
195           785                350

The idea is that we want to get total entries and sum of products sold per user. I'm not sure if this is called a pivot table but someone suggested that? Help me to write mysql query and if there is also date in the column and we want to get entries for today.

1

There are 1 answers

0
Bill Karwin On

You could do self-joins for each attribute. I'm guessing a bit at this, because your example data doesn't match the result you show.

SELECT u.value AS userid,
  t.value AS total_entries,
  s.value AS products_sold
FROM mytable AS u
LEFT JOIN mytable AS t USING (sid)
LEFT JOIN mytable AS s USING (sid)
WHERE u.name='userid'
  AND t.name='total_entries'
  AND s.name='products_sold';