# recursive union query

I have two temp table #d and #c:
``````create table #d(id int, channelid int , name varchar(20), price decimal(5,2))
insert into #d(id, channelid, name, price)values
(1, 1, 'Nokia', 100)
, (2, 2, 'Nokia', 101)
, (3, 3, 'Apple', 102)
, (4, 1, 'Apple', 103)
, (5, 2, 'Nokia', 104)
, (6, 3, 'Nokia', 105)
, (7, 1, 'Nokia', 106)
, (8, 2, 'Apple', 107)
, (9, 3, 'Apple', 108)

create table #c(channelid int , ChannelName varchar(20))
insert into #c(channelid  , ChannelName) values
(1, 'a')
,(2, 'b')
,(3, 'c');

select * from #d;
select * from #c;
``````

It produces:
``````name     a        b        c
Nokia	100.00
Nokia		101.00
Apple			102.00
Apple	103.00
Nokia		104.00
Nokia			105.00
Nokia	106.00
Apple		107.00
Apple			108.00
``````

using:
``````Select  d.name
, case
when c.channelname = 'a' then cast(d.price as nvarchar(10))
else '' end As a
, case
when c.channelname = 'b' then cast(d.price as nvarchar(10))
else '' end As b
, case
when c.channelname = 'c' then cast(d.price as nvarchar(10))
else '' end As c
from #d as d inner join #c as c
on d.channelid = c.channelid
``````

Is there an easier way to produce the same result, for example a recursive union query or something else?
LVL 34
###### Who is Participating?

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

DBACommented:
You could do this recursively, but I don't know why you'd want to.  The SQL that you have works well and is probably faster than recursive SQL, especially if the amount of data grows.

Kent
If you're thinking of using a CTE to pivot your data,  you'll be summing as a consequence:

``````;WITH myCTE AS
(
SELECT  d.Name,
c.ChannelName,
d.Price
FROM    #d d
JOIN    #c c on c.channelid = d.channelid
)
SELECT  Name,
a, b, c
FROM    myCTE
PIVOT ( SUM(Price) FOR ChannelName IN (a, b, c) ) p
``````
Database and Application DeveloperAuthor Commented:
@Kdo,

Regardless of the performance, I like to learn how to apply recursive technique to this problem.

@dsacker,
Sorry, I want to produce:
``````name     a        b        c
Nokia	100.00
Nokia		101.00
Apple			102.00
Apple	103.00
Nokia		104.00
Nokia			105.00
Nokia	106.00
Apple		107.00
Apple			108.00
``````

Mike
Here is a solution with UNION ALL and a CTE:

``````;WITH myCTE AS
(
SELECT Name, Price AS a, NULL  AS b, NULL  AS c FROM #d WHERE ChannelId = 1 UNION ALL
SELECT Name, NULL  AS a, Price AS b, NULL  AS c FROM #d WHERE ChannelId = 2 UNION ALL
SELECT Name, NULL  AS a, NULL  AS b, Price AS c FROM #d WHERE ChannelId = 3
)
SELECT  *
FROM    myCTE
ORDER BY ISNULL(a, 0) + ISNULL(b, 0) + ISNULL(c, 0)
``````
DBACommented:
Hi Mike,

As pointed out, PIVOT is probably more practical in this application, but if you want to use it to learn recursive SQL, I can certainly help.

There are a couple of articles in the DB2 pages that walk you through recursive SQL to convert rows to column or columns to rows.  Your data has every data point in a separate row so you're wanting to convert rows to columns.

http://www.experts-exchange.com/articles/3618/Recursive-SQL-in-DB2-Converting-rows-to-columns.html
http://www.experts-exchange.com/articles/3629/Recursive-SQL-in-DB2-Converting-Columns-to-Rows.html

The technique is identical in SQL Server.  The most significant change between the SQL used by DB2 and SQL Server is that DB2 uses the double-pipe (||) for string concatenation and SQL Server uses plus (+).

For this application, the CTE will need to return the 4 rows that you want.  "name", "a", "b", and "c".  The upper sub-query within the CTE will select all rows from the table where channelid=1.  The lower sub-query will then populate the columns where channelid=2 or 3.

Give it a try and post your SQL.  I'll give you a hand.

Kent
MSSQL Senior EngineerCommented:
There's is nothing recursive in your data. Would be if you have something like levels or hierarchies (master/detail; parent/children; country/cities; ...) so you can go recursive level by level.
So, PIVOT should be the solution for your question.

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.