0

My tables:

categories:

+----+------+
| id | name |
+----+------+
| 1  | blue |
| 2  | red  |
+----+------+

data:

+----------+----------+-------+
|   date   | category | price |
+----------+----------+-------+
|2018-12-17|     1    |   25  |
|2018-12-17|     2    |   12  |
|2018-12-16|     1    |   27  |
|2018-12-16|     2    |   14  |
+----------+----------+-------+

My objective:

+----------+------+-----+
|   date   |   1  |  2  |
+----------+------+-----+
|2018-12-17|  25  |  12 |
|2018-12-16|  27  |  14 |
+----------+------+-----+

Or better:

+----------+------+-----+
|   date   | blue | red |
+----------+------+-----+
|2018-12-17|  25  |  12 |
|2018-12-16|  27  |  14 |
+----------+------+-----+

My question:

Is there an elegant/recommended/easy query to create the resulting table rather than using unions and one query for each category?

1

You can use a SUM(CASE) statement and a GROUP BY in this way:

select 
    date,
    sum(case when category = 1 then price else 0 end) as blue,
    sum(case when category = 2 then price else 0 end) as red
from
    data d
group by
    date
| improve this answer | |
  • Nice trick! Could it be generalized to avoid hard-coding the categories in the query and fetch them from the table instead? – Samuel Dec 17 '18 at 15:27
  • You cannot pivot, you must deal with a dynamic query. stackoverflow.com/a/12005676/3270427 – McNets Dec 17 '18 at 15:29
  • Seems to me you're missing an aggregation function. Furthermore, as stated here, skipping the else clause will simplify the query while still being neutral to the aggregation function. Good article btw, worth reading. – Samuel Dec 17 '18 at 16:38
  • It depends on how many rows for same date/category, but you can use SUM(CASE) – McNets Dec 17 '18 at 16:40
  • Yes that's what I did. Would you mind updating the answer accordingly, so I can accept it? – Samuel Dec 17 '18 at 16:45

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.