Skip to content
Advertisement

Create custom groups on columns and count another column in sql

I’m using sql server and I have a table named Table that looks like this.

SenderId ReciverId ItemCount
1 2 5
1 4 3
1 6 4
2 1 2
2 5 6
3 1 1
4 3 7
4 5 4
5 2 6
5 4 2
5 6 6
6 4 3

I want to make groups of the SenderIds and ReciverIds. Then I would like to total the ItemCount between those groups. The Groupings would be as follows.

SenderId 1 = First. SenderIds 2,3 = Second. SenderIds = 4,5,6 = Third ReciverId 1 = First. ReciverIds 2,3 = Second. ReciverIds = 4,5,6 = Third

I want to return the following

SenderGroup ReceiverGroup ItemCount
First First 0
First Second 5
First Third 7
Second First 3
Second Second 0
Second Third 6
Third First 0
Third Second 13
Third Third 15

I’ve tried a few different queries without much success. Here’s some of what I have so far.

Advertisement

Answer

To get the exact result you are expecting, you can use a cte to first build the custom group and then create fetch the related data from your table joining with cte.

A query will be something like

here is a fiddle

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