Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 How to make this query work

Author  Topic 

ceema
Yak Posting Veteran

80 Posts

Posted - 2006-08-07 : 01:17:14
Hello,
I have two tables without any relationship

one is table1 with fields col1 and col2
second is table2 with fields col3 and col4

in tablle1 I have some values like


Code:

col1 col2
-----------
1 A
2 B
3 C


and in table2 I have

Code:

col3 col4
----------
2 XX
3 YY
1 ZZ
4 NN

I want to diplsy it like

Code:

A xx yy zz NN

B xx yy zz NN

C xx yy zz NN

Any way?

Thank you
Ceema

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-08-07 : 01:24:30
what is the relationship between table1 & table2 ?


KH

Go to Top of Page

ceema
Yak Posting Veteran

80 Posts

Posted - 2006-08-07 : 01:38:07
quote:
Actually there is no relation, that's the problem. DO you think there is any way?


Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-08-07 : 01:43:03
[code]declare @table1 table
(
col1 int,
col2 varchar(10)
)

declare @table2 table
(
col3 int,
col4 varchar(10)
)

insert into @table1
select 1, 'A' union all
select 2, 'B' union all
select 3, 'C'

insert into @table2
select 2, 'XX' union all
select 3, 'YY' union all
select 1, 'ZZ' union all
select 4, 'NN'

select col2,
max(case when col3 = 1 then col4 end),
max(case when col3 = 2 then col4 end),
max(case when col3 = 3 then col4 end),
max(case when col3 = 4 then col4 end)
from @table1 t1 cross join @table2 t2
group by col2[/code]


KH

Go to Top of Page

ceema
Yak Posting Veteran

80 Posts

Posted - 2006-08-07 : 02:02:15
Khtan,

Thank you so much, this will do.

Regards
Ceema
Go to Top of Page

chiragkhabaria
Master Smack Fu Yak Hacker

1907 Posts

Posted - 2006-08-07 : 02:13:14
OR


Declare @QryString varchar(8000)
Create TAble ##tbl1
(
col1 varchar(8),
col2 varchar(8)
)

Create TAble ##tbl2
(
col3 varchar(8),
col4 varchar(8)
)

Insert ##tbl1
Select '1','A' Union All
Select '2','B' Union All
Select '3','C'

Insert ##tbl2
Select '2','XX' Union All
Select '3','YY' Union All
Select '1','ZZ' Union All
Select '4','NN'


-- Pivot the Table Query
Set @QryString = 'Select '
Select @QryString = @QryString + 'Max(Case When Col4 = ''' + Col4 + ''' Then Col4 End )' + Col4 + ',' From ##tbl2
--Remove the last ','
Select @Qrystring = Left(@QryString ,len(@QryString)-1)
Select @QryString = @QryString + ' Into ##tbl3 From ##Tbl2 '

-- Now Insert the values into 3rd table
Exec(@QryString)

--Now finally run the query :-)

Select t1.Col1,t3.* from ##Tbl3 t3,##tbl1 t1
-- Drop The Temp Tables

Drop Table ##tbl2,##tbl1,##tbl3


Chirag
Go to Top of Page
   

- Advertisement -