查询或视图中的动态列
dynamic columns in Query Or view
请帮助我。我如何在查询中显示动态列。我想要一个视图。
提前致谢
我的Out是这样的
select SectionID,
Column1, Column2, Column3
from
(
select S.SectionID,ColumnDataName, ColumnDescription,
row_number() over(partition by S.SectionID
order by SectionTableColumnID) seq
from dbo.SectionTableColumn vt
INNER JOIN dbo.Section S ON S.SectionID = vt.SectionID
) d
pivot
(
max(ColumnDescription)
for ColumnDataName in ( Column1, Column2, Column3)
) piv;
无法创建具有动态列数的视图。您需要指定 ColumnDataName 的所有值才能使其正常工作。
您需要调整结果,下面是一个如何创建视图的示例:
CREATE TABLE
xxx(SectionID int, ColumnDescription varchar(10), ColumnDataName varchar(10))
INSERT xxx values(2, 'dgj', 'column1')
INSERT xxx values(2, 'ash', 'column2')
INSERT xxx values(8, 'lkhsdh', 'column2')
go
CREATE VIEW v_xxx as
SELECT SectionId, [column1],[column2],[column3]
FROM xxx
PIVOT
(min(ColumnDescription)
FOR ColumnDataName
in([column1],[column2],[column3])
)AS p
go
SELECT * FROM v_xxx
结果:
SectionId column1 column2 column3
2 dgj ash NULL
8 NULL lkhsdh NULL
请帮助我。我如何在查询中显示动态列。我想要一个视图。 提前致谢
select SectionID,
Column1, Column2, Column3
from
(
select S.SectionID,ColumnDataName, ColumnDescription,
row_number() over(partition by S.SectionID
order by SectionTableColumnID) seq
from dbo.SectionTableColumn vt
INNER JOIN dbo.Section S ON S.SectionID = vt.SectionID
) d
pivot
(
max(ColumnDescription)
for ColumnDataName in ( Column1, Column2, Column3)
) piv;
无法创建具有动态列数的视图。您需要指定 ColumnDataName 的所有值才能使其正常工作。
您需要调整结果,下面是一个如何创建视图的示例:
CREATE TABLE
xxx(SectionID int, ColumnDescription varchar(10), ColumnDataName varchar(10))
INSERT xxx values(2, 'dgj', 'column1')
INSERT xxx values(2, 'ash', 'column2')
INSERT xxx values(8, 'lkhsdh', 'column2')
go
CREATE VIEW v_xxx as
SELECT SectionId, [column1],[column2],[column3]
FROM xxx
PIVOT
(min(ColumnDescription)
FOR ColumnDataName
in([column1],[column2],[column3])
)AS p
go
SELECT * FROM v_xxx
结果:
SectionId column1 column2 column3
2 dgj ash NULL
8 NULL lkhsdh NULL