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
 General SQL Server Forums
 New to SQL Server Programming
 Sub Query

Author  Topic 

David Wadsworth
Starting Member

17 Posts

Posted - 2010-10-18 : 07:45:04
Hi All,

I have been searching for this answer all morning but suspect I dont know the correct question to ask ....

Table 1 - Meat
UIN Product
1 Beef
2 Chicken
3 Tuna

Table 2 - Properties
UIN Property Meat
1 Red Beef
2 Tasty Chicken
3 Expensive Beef
4 White Tuna

I need to return each row from table a with all entries from table 2 so -
Row 1 - Beef - Red+Expensive
Row 2 - Chicken - Tasty
Row 3 - Tuna - White

I know this may be a bit basic but honestly I have never had to query this way before ...

My questions are this what would the query look like and how do I access the results?

Sorry if this is a bit basic ...

David

namman
Constraint Violating Yak Guru

285 Posts

Posted - 2010-10-19 : 09:55:07
Try this ....


declare @t1 table(UIN int, Product varchar(20))
insert into @t1 values(1, 'Beef')
insert into @t1 values(2, 'Chicken')
insert into @t1 values(3, 'Tuna')

declare @t2 table(UIN int, Property varchar(20), Meat varchar(20))
insert into @t2 values(1, 'Red', 'Beef')
insert into @t2 values(2, 'Tasty', 'Chicken')
insert into @t2 values(3, 'Expensive', 'Beef')
insert into @t2 values(4, 'White', 'Tuna')

;with temp as (select Product, (select '+'+Property from @t2 where Meat = t1.Product for xml path('')) as note from @t1 t1)
select Product, substring(note,2,len(note)) as note from temp


-- result
Product note
Beef Red+Expensive
Chicken Tasty
Tuna White
Go to Top of Page

jcelko
Esteemed SQL Purist

547 Posts

Posted - 2010-10-19 : 11:59:37
Google the term "EAV design" or "Entity-Attribute-Value" and find out why we don't write DDL like this.

--CELKO--
Books in Celko Series for Morgan-Kaufmann Publishing
Analytics and OLAP in SQL
Data and Databases: Concepts in Practice
Data, Measurements and Standards in SQL
SQL for Smarties
SQL Programming Style
SQL Puzzles and Answers
Thinking in Sets
Trees and Hierarchies in SQL
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-10-19 : 12:46:44
see scenario 3

http://visakhm.blogspot.com/2010/01/multipurpose-apply-operator.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -