以下是表格和要求清单;
表A
ID Description Code
1 Desc1 CodeA
2 Desc2 CodeB
3 Desc3 CodeC
4 Desc4 CodeD
5 Desc5 CodeE
表B (代码之间的关系匹配,包括他们自己)
ID TableA_ID TableA_ID_Relation
1 1 1
2 1 2
3 2 1
4 2 2
5 2 3
6 2 4
7 3 2
8 3 3
9 4 1
10 4 3
11 4 4
12 5 1
13 5 2
14 5 3
15 5 4
16 5 5
上面表A和B中的请求列表(关系应以BIT类型显示)
ID Description CodeA CodeB CodeC CodeD CodeE
1 Desc1 CodeA 1 1 0 0 0
2 Desc2 CodeB 1 1 1 1 0
3 Desc3 CodeC 0 1 1 0 0
4 Desc4 CodeD 1 0 1 1 0
5 Desc5 CodeE 1 1 1 1 1
我已经开始使用Pivot查询。但是,我还没有取得好成绩。 这是整个结构以及查询和输出。
表结构:
CREATE TABLE TableA (
[ID] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL
, [Description] NVARCHAR(50) NULL
, [Code] NVARCHAR(10) NULL)
CREATE TABLE TableB (
[ID] INT IDENTITY(1,1) NOT FOR REPLICATION NOT NULL
, [TableA_ID] INT NULL
, [TableA_ID_Relation] INT NULL)
INSERT INTO TableA([Description], [Code])
VALUES('Desc1','CodeA')
,('Desc2','CodeB')
,('Desc3','CodeC')
,('Desc4','CodeD')
,('Desc5','CodeE')
INSERT INTO TableB([TableA_ID], [TableA_ID_Relation])
VALUES(1,1)
,(1,2)
,(2,1)
,(2,2)
,(2,3)
,(2,4)
,(3,2)
,(3,3)
,(4,1)
,(4,3)
,(4,4)
,(1,1)
,(2,2)
,(3,3)
,(4,4)
,(5,5)
查询:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Code)
FROM TableA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
PRINT @cols
set @query = 'SELECT ID,Description, ' + @cols + ' from
(
SELECT A.ID, A.Description, A.Code, B.TableA_ID_Relation
FROM TableA A
LEFT OUTER JOIN TableB B ON B.TableA_ID_Relation = A.ID
) x
pivot
(
MAX(Code)
for Code in (' + @cols + ')
) p '
PRINT @query
execute(@query);
结果虽然不是我想要的结果;
到目前为止,我已尝试进行一次查询,但进展顺利。 在我进行某种复杂的开发之前,我想听听你的意见。
答案 0 :(得分:1)
P.S。
样本集只是给定
DECLARE @cols AS NVARCHAR(MAX),
@cols_isnull AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Code)
FROM TableA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
select @cols_isnull = STUFF((SELECT ',isnull(' + QUOTENAME(Code) + ',0) as ' + QUOTENAME(Code)
FROM TableA
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
PRINT @cols
set @query = 'SELECT id,description,code,' + @cols_isnull + ' from
(
SELECT a1.id,a1.code,a1.Description,a2.Code as code2,1 as indication
FROM TableB b
join TableA a1
on a1.id = b.TableA_ID
join TableA a2
on a2.id = b.TableA_ID_Relation
) x
pivot
(
MAX(indication)
for Code2 in (' + @cols + ')
) p
'
PRINT @query
execute(@query);