Skip to content
Advertisement

SQL create new columns based on product classification and client buying the product

I have a table with clients and a table of products each client is buying

To retrive each client interest in any product I wrote the following SQL statement

SELECT 
t1.ClientID
,t2.ProductID
  FROM [DTBA].[dbo].[Client] t1
  inner join [DTBA].[dbo].[Product] t2 on t2.ClientID = t1.ClientID

This will return me a full list of client and product they are buying as per below

Client ID Product ID
100017 7000
100018 7001
100019 7000
100021 7002
100024 7001
100025 7001
100028 7003

What I would like to do is to create a SQL query that will return me the clientID and a column for each productID with result of a binary file if the client is buying a product or not as per the example below

ClientID ProductID 7000 7001 7002 7003
100017 7000 1 0 0 0
100018 7001 0 1 0 0
100019 7000 1 0 0 0
100021 7002 0 0 1 0
100024 7001 0 1 0 0
100025 7001 0 1 0 0
100028 7003 0 0 0 1

I would appreciate any help as to define each cols and retrive the binary info cols

Advertisement

Answer

I think the easiest way to answer your question is going to be with a whole bunch of case statements. Something like this:

SELECT
ClientID,
ProductID,
SUM( CASE WHEN ProductID = 7000 THEN 1 ELSE 0 END ) AS 7000, 
SUM( CASE WHEN ProductID = 7001 THEN 1 ELSE 0 END ) AS 7001,
SUM( CASE WHEN ProductID = 7002 THEN 1 ELSE 0 END ) AS 7002,
SUM( CASE WHEN ProductID = 7003 THEN 1 ELSE 0 END ) AS 7003
  FROM [DTBA].[dbo].[Client] t1
  inner join [DTBA].[dbo].[Product] t2 on t2.ClientID = t1.ClientID
  GROUP BY 1, 2 
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement