Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

sql - JOIN three tables and aggregate data from multiple rows for every DISTINCT row in separate column

JOIN three tables and aggregate data from multiple rows for every DISTINCT row in separate column

i have a table where one item is mapped with multiple items.

Key 1 | Key 2
1       2
1       5
1       6
1       4
1       8

I have another table like this

Key 1 | ShortKey1Desc
1       'Desc short'

i have one more table where i have data like this

Key 1 | Description
1       'Desc a'
1       'Desc c'
1       'Desc aa'
1       'Desc tt'

i need to write a sql query for my view where table would be generated like this

Key 1 | AllKeys2ForKey1 | AllDescriptionsForKey1           | ShortKey1Desc
1     | 2;5;6;4;8       | Desc a; Desc c; Desc aa; Desc tt | Desc short

Key 1 is a string type field so i need to join them table using that string key

what i'm trying is to create a view for comfortable data access. need to create a query what will not take ages. i already tried to do it with Functions but it takes ages for load.

any help on this one would be highly appreciated. thanks a lot

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you are unable to change the data structures to make a more efficient query, this will work:

--Populate sample data
SELECT 1 as key1,       2  as key2 INTO #tbl1
UNION ALL SELECT 1,       5 
UNION ALL SELECT 1,       6 
UNION ALL SELECT 1,       4 
UNION ALL SELECT 1,       8 

SELECT 1  as key1,     'Desc short' as shortkeydesc INTO #tbl2

SELECT 1   as key1,    'Desc a'  as [description] INTO #tbl3
UNION ALL SELECT 1,       'Desc c' 
UNION ALL SELECT 1,       'Desc aa' 
UNION ALL SELECT 1,       'Desc tt' 

--Combine data into semi-colon separated lists
SELECT 
key1
,STUFF(
    (
    SELECT
      ';' + CAST(t2.key2 AS VARCHAR(10))
    FROM #tbl1 t2
    WHERE t2.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
,STUFF(
    (
    SELECT
      ';' + tbl2.shortkeydesc
    FROM #tbl2 tbl2
    WHERE tbl2.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
,STUFF(
    (
    SELECT
      ';' + tbl3.[description]
    FROM #tbl3 tbl3
    WHERE tbl3.key1 = tbl1.key1
    FOR XML PATH('')
    ), 1, 1, ''
  )
FROM #tbl1 tbl1
GROUP BY tbl1.key1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...