0

JOIN 三个表并为单独列中的每个 DISTINCT 行聚合来自多行的数据

我有一张表,其中一个项目与多个项目映射。

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

我有另一张这样的桌子

Key 1 | ShortKey1Desc
1       'Desc short'

我还有一张桌子,上面有这样的数据

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

我需要为我的视图编写一个 sql 查询,其中将生成这样的表

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

键 1 是一个字符串类型字段,所以我需要使用该字符串键加入它们的表

我正在尝试创建一个舒适的数据访问视图。需要创建一个不需要很长时间的查询。我已经尝试过使用 Functions 来实现,但加载需要很长时间。

对此的任何帮助将不胜感激。多谢

4

3 回答 3

1

假设您无法更改数据结构以进行更有效的查询,这将起作用:

--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
于 2012-05-15T11:19:32.290 回答
0

要将行转换为一个结果,您需要将值保存在变量中,下面是示例代码,只是为了给您一个想法

Declare @AllKeys2ForKey1 varchar(50)
set @AllKeys2ForKey1 = ''
SELECT @AllKeys2ForKey1 = @AllKeys2ForKey1  + cast([Key 2] as varchar(3)) + ','
  FROM [AllKeys2ForKey1Table] where [KEY 1] = 1


Declare @AllDescriptionsForKey1 varchar(100)
set @AllDescriptionsForKey1 = ''
SELECT @AllKeys2ForKey1 = @AllKeys2ForKey1  + [Description] + ','
  FROM [AllDescriptionsForKey1Table] where [KEY 1] = 1

Declare @ShortKey1Desc varchar(100)
set @ShortKey1Desc = ''
SELECT @ShortKey1Desc = @ShortKey1Desc  + [ShortKey1Desc] + ','
  FROM [ShortKey1DescTable] where [KEY 1] = 1  


Select [KEY 1], 
        substring(@AllKeys2ForKey1,1,len(@AllKeys2ForKey1) - 1) as 'AllKeys2ForKey1 ',
        substring(@AllDescriptionsForKey1,1,len(@AllDescriptionsForKey1) - 1) as 'AllDescriptionsForKey1',
        substring(@ShortKey1Desc,1,len(@ShortKey1Desc) - 1)  as 'ShortKey1Desc'
from Table where [KEY 1]= 1 
于 2012-05-15T09:45:59.027 回答
0

你必须编写 CLR 聚合函数来解决这个问题。用于编写 CLR 聚合函数: 1:运行 Microsoft Visual Stadio 2:创建新项目 3:然后选择数据项目 4:CLR 聚合函数

创建聚合函数后创建查询,如下所示

 Select A.Key1, OwnAggregateFn(B.Description), OwnAggregateFn(C.Key2), ...
 From A
 inner join B ON B.Key1 = A.Key1
 inner join C ON C.Key1 = A.Key1
 ... 
 Group By A.Key1
于 2012-05-21T23:17:00.480 回答