Skip to content
Advertisement

Summarise data by date with percentages using SQL PIVOT

I have some data that looks something like this:

Essentially I need to (in SQL) pivot this data somehow in to something like this:

Where the SOMEPROPERTY% is the % of the total items that day where the property is set to 1 (it can be 1 or 0).

I may also need to add CATEGORY as an extra level so that the data is grouped by that too:

Can anyone assist?

Needs to be a single SQL statement – I tried doing it using GROUP BY but it got quite messy and was giving odd results. I think it may be possible with PIVOT but I can’t find a good example and it’s not the easiest command to play with.

n.b. I know that this sort of stuff would normally be done in the presentation layer rather than directly in SQL but I don’t have that option for where this is needed.

Thanks.

Advertisement

Answer

Use conditional aggregation. I’m going to assume SQL Server for this purpose:

There is no need to put year/month/day in separate columns.

The equivalent function in Oracle would be trunc(eventdatetime). There is similar functionality in whatever database you are using.

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