2

I have two tables, first the table food and Second is Activity:

INSERT INTO food
    (`id`, `foodName`)
VALUES
    (1, 'food1'),
    (2, 'food2'),
    (3, 'food3'),
    (4, 'food4'),
    (5, 'food5'),
    (6, 'food6'),
;
CREATE TABLE Activity
    (`id` int,`place` varchar(14),`food_id` int,`timing` TIME,`date_and_time` DATETIME)
;
INSERT INTO Activity
    (`id`,`place`, `food_id`,`timing`,`date_and_time`)
VALUES
    (1, 'place1', 1, '10:30am','2013-05-01'),
    (2, 'place1', 1, '12:30pm','2013-05-01'),
    (3, 'place1', 1, '04:30pm','2013-05-01'),
    (4, 'place2', 2, '10:30am','2013-05-02'),
    (5, 'place2', 2, '12:30pm','2013-05-02'),
    (6, 'place2', 2, '4:30pm','2013-05-02'),
    (7, 'place1', 2, '10:30am','2013-05-02'),
    (8, 'place1', 2, '12:30pm','2013-05-02'),
    (9, 'place1', 2, '4:30pm','2013-05-02'),
    (10, 'place2', 3, '10:30am','2013-05-03'),
    (11, 'place2', 3, '12:30pm','2013-05-03'),
    (12, 'place2', 3, '4:30pm','2013-05-03')
;

For now I'm using the following query:

SELECT 
    a.activity_type AS Activity, 
    COUNT(DISTINCT p.id) AS Products,
    CONVERT(GROUP_CONCAT(p.category_id SEPARATOR ',  ') USING utf8) 
      AS Categories
FROM 
    food AS p
  JOIN 
    ( SELECT activity_type
           , prod_id
      FROM activity 
      WHERE activity_type <> '' 
      GROUP BY activity_type
             , prod_id
    ) AS a
    ON p.id = a.prod_id
GROUP BY 
    activity_type
ORDER BY 
    Products DESC ;

Could you please help me, I need output in the below format:

place | food_id | Timings             |                              |
      |         |---------------------|Date                          |
      |         |Time1 |Time2 | Time3 |                              |
---------------+----------+------------------------------------------|
place1 | 1      | 10:30am| 12:30pm| 4:30pm |2013-05-01(MAX timestamp)|          
place2 | 1      | 10:30am| 12:30am| 4:30am |2013-05-01(MAX timestamp)|
  • 1
    Are you sure that is the correct query? You have columns being like activity_type, prod_id and category_id but those are not in your tables that you provided. – Taryn May 1 '13 at 12:08
  • I'm sorry to mention this, for some reasons i changed the columns name. – user2100659 May 1 '13 at 12:33
1

If your date_and_time values are always the same, use this query:

select place, food_id, '10:30am' as Time1, '12:30pm' as Time2, '4:30pm' as Time3, DATE_FORMAT(MAX(date_and_time), '%Y-%m-%d') as Date from Activity group by food_id, place;
-1

I think, it's better to use PIVOT. the below link shows how it works : http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

  • MySQL has no PIVOT clause. Your link is for SQL-Server. – ypercubeᵀᴹ Jul 11 '14 at 9:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.