我有如下要求。
我有一个表,其中所有字符放在一列中,我需要使用这些信息创建一个表,每个字符都有一个列。
实施例: 来源表:
article id | char id | char value
1 | 1 | book
1 | 2 | yes
1 | 3 | 100
2 | 1 | cd
2 | 2 | No
目的地表
article id | type | lendable | number of pages
1 | book | yes | 100
2 | cd | no | NULL
我们可以通过两个内部联接来做到这一点,但如果有更多的列,那么我将很难。这样做有直接的方法吗?
提前感谢您的帮助。
答案 0 :(得分:0)
这可以使用INSERT INTO..SELECT
完成。
INSERT INTO destinationTable(articleid, type, lendable, NumberOfPages)
SELECT ArticleID,
MAX(CASE WHEN charID = 1 THEN charValue END) type,
MAX(CASE WHEN charID = 2 THEN charValue END) lendable,
MAX(CASE WHEN charID = 3 THEN charValue END) NumberOfPages
FROM SourceTable
GROUP BY ArticleID
答案 1 :(得分:0)
不是构建一个“完成所有”的单一花哨查询,而是创建单独的小查询更简单,更清晰 - 每种类型的更新都有一个。
这样做有以下好处:
答案 2 :(得分:0)
您可以使用 pivot 或 Max(值)..分组来“旋转”您的表格,然后使用插入选择.. 或选择*进入...
的 PIVOT SQL FIDDLE DEMO 强>
with CTE_SourceTable
as
(
select article_id, [1] as type, [2] as lendable, [3] as [number of pages]
from SourceTable
pivot
(
max(char_value)
for char_id in ([1],[2],[3])
) as PVT
)
select *
into DestinationTable
from CTE_SourceTable
<强> Max(value)..Group By SQL FIDDLE DEMO 强>
with CTE_SourceTable
as
(
select article_id, [1] as type, [2] as lendable, [3] as [number of pages]
from SourceTable
pivot
(
max(char_value)
for char_id in ([1],[2],[3])
) as PVT
)
select *
into DestinationTable
from CTE_SourceTable