Skip to content
Advertisement

Query help on sales transaction table

I have a table that contains transaction level sales data. I am trying to satisfy a reporting request as efficiently as possible which I don’t think I am succeeding at right now. Here is some test data:

And I need to represent both individual item sales as well as total transaction sales for every transaction in which the specified items were present. Examples:

Returns this:

And I can get the total transaction sales in which a single item was present this way:

But I am failing to find a clean, efficient, and dynamic way to return it all in one query. The end user will be able to specify the items/stores/dates for this report. The end result I would like to see is this:

Advertisement

Answer

If I understand correctly, you can use window functions to summarize by transaction and then aggregate:

Here is a db<>fiddle.

You can add appropriate filtering in the subquery.

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