Forum Discussion

tanvip's avatar
tanvip
Copper Contributor
Aug 08, 2023

anyone please help to write a query, urgent requirement

Hi

I am having two tables contact and contact category as mentioned below now 

 contact category

Contact categoryidtype
1phone
2mobile

contact

IDValueContact CategoryId
197867445453                              1
114343556677                              2
29783673526                              1
3                               1
31465276127                              2
418397387309                              2
50281938978                              2

 i want to get result entry of type phone and when 'phone' is not available then 'mobile' should display 
as shown below 

IDValue
197867445453
29783673526
31465276127
418397387309
50281938978

please help me how to write sql quey to get above result 

thank you.

  • LainRobertson's avatar
    LainRobertson
    Silver Contributor

    tanvip 

     

    Here's the T-SQL I used to stage your data based on your previous post:

     

    CREATE TABLE [contactCategory]
    (
    	[id] [int] NOT NULL
    	, [type] [varchar](16) NOT NULL
    )
    GO
    
    CREATE TABLE [contact]
    (
    	[id] [int] NOT NULL
    	, [value] [varchar](16)
    	, [typeId] [int] NOT NULL
    )
    GO
    
    INSERT INTO
    	[contactCategory]
    VALUES
    	(1, 'phone')
    	, (2, 'mobile')
    GO
    
    INSERT INTO
    	[contact]
    VALUES
    	(1, '97867445453', 1)
    	, (1, '14343556677', 2)
    	, (2, '9783673526', 1)
    	, (3, null, 1)
    	, (3, '1465276127', 2)
    	, (4, '18397387309', 2)
    	, (5, '0281938978', 2)
    GO

     

    Here's a query that does what you've asked for:

     

    SELECT
    	[data].[id]
    	, [data].[value]
    FROM
    (
    	SELECT
    		c.id
    		, c.value
    		, ROW_NUMBER() OVER (
    			PARTITION BY
    				c.id
    			ORDER BY
    				c.typeId
    		) AS [rowNumber]
    	FROM
    		[contact] AS c INNER JOIN
    		[contactCategory] AS cc ON TRIM(c.value) <> '' AND c.typeId = cc.id
    ) AS [data]
    WHERE
    	[data].[rowNumber] = 1;

     

    Output from the query

     

     

    Cheers,

    Lain

Resources