Skip to content
Advertisement

How to make a separate column for each condition using one sql query?

I have a table with the data in the following format:

It contains the number of seconds each user has watched tv on a specific day. One user can have more than one watching session per day. For example, user 1 has watched tv three times on Monday.

What I need to do is to create a separate column for each day, which will contain the total number of seconds watched on this day for each user. In other words, I need to have one row and seven columns for each user. The column would be: Monday, Tuesday, Wednesday, etc.

It would look like this:

Right now, I can do that using the following script:

The script does its job, but I’m pretty sure it’s not the most efficient way to do what I want. And I’m looking for a way to make this script better and shorter. I know that there definitely is a much simpler solution, but I don’t even know how to ask a question correctly.

Could anyone help me please or point to a similar question? I’d really appreciate it!

Advertisement

Answer

Use aggregation:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement