0

I am currently working on developing some association mining for a table that contains product information. Put simply, the core table essentially looks like this:

enter image description here

I am currently grouping by the product and counting the total amount of distinct transaction IDs to see how many transactions a specific product is part of. This then turns the table into this: enter image description here

My question is, once I do the group by is there a way to pull out the actual transaction ID without getting rid of the grouping? Maybe a way to concatenate the IDs into another column so it would look something like this:

enter image description here

Definitely open to other suggestions on how to get back to the original IDs. Thank you!

John
  • 69
  • 3

2 Answers2

0

SQL Server 2016+

SELECT 
    product
   ,count([transaction id])  as [count of transaction id]
   ,STRING_AGG(ID,',') as IDs
FROM YourTable
GROUP BY product
Gabriel Durac
  • 2,610
  • 1
  • 12
  • 13
0

You can try this. DBFIDDLE

SELECT a.Product
    ,a.[count of transactions]
    ,SUBSTRING(a.all_transactions, 0, LEN(a.all_transactions)) [IDs]
FROM (
    SELECT Product
        ,COUNT(DISTINCT TransactionId) [count of transactions]
        ,(
            SELECT DISTINCT CAST(TransactionId AS VARCHAR(10)) + ',' [text()]
            FROM dbo.Products inner_p
            WHERE inner_p.Product = Products.Product
            --GROUP BY inner_p.Product
            FOR XML PATH('')
                ,TYPE
            ).value('.', 'NVARCHAR(MAX)') [all_transactions]
    FROM dbo.Products
    GROUP BY Product
    ) a

Output:

enter image description here

Sowmyadhar Gourishetty
  • 1,843
  • 1
  • 8
  • 15
  • Hi Sowmyadhar, this got the job done for single product combinations! I was wondering if it is also possible to follow this sort of logic for double product combinations? So the total count of transactions that have both apples and oranges and the IDs that contain both. Hope that makes sense. – John Aug 20 '20 at 18:20
  • I didn't understand the double product combinations, can you update your question with sample example. – Sowmyadhar Gourishetty Aug 20 '20 at 18:27