Click here to Skip to main content
14,690,956 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi volks,

I need help on here on this.

I´ve got this structure containing multiple records for a user.
USERID   CITY         CITY_ID    TYPE
1	     London	      6	         1
1	     Liverpool    2	         2


Based on the type of 2 fields need to be populated 

When type = 1: STOREDID should be populated
When type = 2: OUTLETID should be populated

The final output should look like the following:

USERID | STORE_ID  | OUTLETID
1      | 6         | 2


CREATE TABLE TMP_USERS_TOUCH_POINT
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY
,USERID INT NOT NULL
,CITY NVARCHAR(100) NOT NULL
,STORE_TYPE INT NOT NULL
,CITY_ID INT
)

INSERT INTO TMP_USERS_TOUCH_POINT
VALUES (1,'LONDON',1,6)
,(2,'LIVERPOOL',1,2)


How can I achieve such a result?


Thanks for your help upfront..

What I have tried:

Using a pivot but did not succeed
Posted
Updated 3-May-20 7:08am
v2
Comments
hari19113 3-May-20 11:01am
   
Is your given data wrong, it doesn't match the question and values.

1 solution

The following code works with below data.

ID	USERID	CITY	         STORE_TYPE	  CITY_ID
1	1	    LONDON	         1	          6
2	1	    LIVERPOOL        2	          2


  SELECT	A.USERID		, 			
			MAX(CASE WHEN A.STORE_TYPE = 1 
					 THEN A.CITY_ID END) AS STORE_ID,
			MAX(CASE WHEN A.STORE_TYPE = 2 
					 THEN A.CITY_ID END) AS OUTLETID
	FROM	TMP_USERS_TOUCH_POINT A
GROUP BY	A.USERID


Output:
USERID	  STORE_ID	OUTLETID
1	      6	        2


Hope this helps you.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900