1

以下のような要件があります。

すべての文字が 1 つの列に配置されたテーブルがあり、その情報を使用して、文字ごとに 1 つの列を持つテーブルを作成する必要があります。

例: ソース テーブル:

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

2 つの内部結合でこれを行うことができますが、それ以上の列がある場合は難しくなります。これを行う簡単な方法はありますか??

助けてくれてありがとう。

4

3 に答える 3

0

pivotまたはMax(value)..Group byを使用してテーブルを「ピボット」し、次にInsert into select..またはSelect * into...
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
于 2013-03-28T07:17:30.413 に答える
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
于 2013-03-28T05:19:40.450 に答える
0

「すべてを実行する」単一の派手なクエリを作成するよりも、個別の小さなクエリ (更新の種類ごとに 1 つずつ) を作成する方が簡単で明確です。

これには、次の利点があります。

  • メンテナンスの改善 - 別の新しいタイプのカスタム マッピングを追加したり、既存のものを変更したりするのは簡単です
  • はるかに明確で理解しやすい - 明確さは優れたプログラミングの基礎です
  • 変更セットが小さくまとまりがあるため、テストがはるかに簡単になります
于 2013-03-28T05:21:42.910 に答える