-1
Primary    Secondary
-----------------------------------
UST         MUN
Data        NULL
Tele        Data
Sun         Data
RMDS        Data
Data        NULL
Mor         NULL
UST         NULL
Data        Bridge

I want to check if values of "Secondary" is already in "primary" then it should come as "primary" but if it is not in "primary" values it must come under "Secondary" column only.

Here I want output as:

Primary  Secondary
------  -----------
UST      MUN
Data     Bridge
Tele
Sun
RMDS
Mor
Himani
  • 41
  • 5

2 Answers2

1

A UNION (rather that UNION ALL) will return all distinct values you require:

SELECT Primary
FROM MyTable

UNION

SELECT Secondary
FROM MyTable
WHERE Secondary IS NOT NULL
Serge
  • 3,986
  • 2
  • 17
  • 37
  • Thanks ,But Null value is also coming in output, but i do not want this – Himani Feb 15 '17 at 10:14
  • select * from (select primaryFeed as feed from #feedinfo union select SecondaryFeed from #feedinfo) fedd where feed is not null – Himani Feb 15 '17 at 10:16
  • Hey can you answer my above query ? – Himani Feb 16 '17 at 08:41
  • @Himani, I updated the query and added `WHERE Secondary IS NOT NULL`. Or, is it the case that you want the output in two columns? – Serge Feb 16 '17 at 12:22
  • This is fine, but if i want to add one more column in output as 'type' and it should output by checking ( 2 conditions , 1) if 2 col value is in 1st col then 'type' is 'primary' but 2) if 2nd col is not in 1st col then 'type' is secondary – Himani Feb 16 '17 at 12:52
  • Primary type ------ ----------- UST primary Data primary Tele primary Sun primary RMDS primary Mor primary MUN Secondary Bridge Secondary here MUN and Bridge were not in 1st col so they should come as secondary i tried this: – Himani Feb 16 '17 at 12:55
  • select pri as feed,'type' = (case when sec not in (select distinct pri from #feedinfo ) then 'sec' else 'pri' end) from #feedinfo union select sec ,'type' = (case when sec in (select distinct pri from #feedinfo ) then 'pri' else null end) from #feedinfo – Himani Feb 16 '17 at 12:56
0

Both rows in one output is not possible since you dont have the combining factor. How will the db know that UST - MUN should come in same row and not UST - Bridge .

What you can get it in a two different outputs and build your programming logic around it.

For first row you can do :

SELECT * FROM 
(
SELECT t1.`primary` FROM tableName t1 
UNION
SELECT t1.`primary` FROM tableName t1 
INNER JOIN tableName t2 ON t1.primary = t2.`secondry`
) AS test1

And for second you can do :

SELECT DISTINCT t2.`secondry` FROM tableName t1 
RIGHT JOIN tableName t2 ON t1.primary = t2.`secondry` 
WHERE  t1.primary IS  NULL AND t2.secondry IS NOT NULL 
Bhavik Patel
  • 1,044
  • 1
  • 15
  • 33