在单独的列
中为每个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是字符串类型字段,因此我需要使用该字符串键
将它们连接起来我正在尝试创建一个舒适的数据访问视图。需要创建一个不需要多长时间的查询。我已经尝试使用函数来完成它,但是加载需要很长时间。
对此的任何帮助都将受到高度赞赏。非常感谢
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分:0)
您必须编写CLR聚合函数才能解决此问题。 用于写入CLR聚合函数: 1:运行Microsoft Visual Stadio 2:创建新项目 3:然后选择Data Project 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