1

表1

Code, desc, type id

01    Rajan    1
01    Sajan    1
01    Vijayan  2
01    Suresh   3
01    Caresh   4
01    Sujesh   4
01    vikran   4
02    desk     1
02    card     2
02    villa    2
02    megash   2
02    supan    3
....

タイプIDごとにテーブルを表示したい

期待される出力

Code type-1 type-2 type-3 type-4

01   Rajan  Vijayan suresh caresh
01   Sajan  null    null   Sujan
01   null   null    null   vikran
02   desk   card    supan  null
02   null   villa   null   null
02   null   megash  null   null

上記の条件を照会する方法

クエリヘルプが必要

4

2 に答える 2

2

したがって、最初にデータをステージングします。後で ID 行 ID を追加していることに注意してください。

IF OBJECT_ID('tempdb..#test') IS NOT NULL
   drop table #test
IF OBJECT_ID('tempdb..#Numbered') IS NOT NULL
   drop table #Numbered

 CREATE TABLE #test (Code CHAR(2), [DESC] varchar(10), [type id] INT, RowNumber INT IDENTITY(1,1))


INSERT #test 
    VALUES ('01', 'Rajan', 1),
           ('01' ,'Sajan', 1),
           ('01' ,'Vijayan', 2),
           ('01' ,'Suresh', 3),
           ('01' ,'Caresh', 4),
           ('01' ,'Sujesh', 4),
           ('01' ,'vikran', 4),
           ('02' ,'desk', 1),
           ('02' ,'card' ,2),
           ('02' ,'villa', 2),
           ('02', 'megash', 2),
           ('02', 'supan', 3)

次に、その行 ID を使用して各名前がコードのどの行に続くかを計算する保持領域を作成します。

  CREATE TABLE #Numbered
      (
       RowNum int, Code CHAR(2), [type] VARCHAR(10), [DESC] VARCHAR(10)
       )

   INSERT #Numbered
         SELECT (select count(*) from #test where code=t1.Code AND [type id]=t1.[type id] AND  RowNumber<=t1.RowNumber),
                 code, 
                [type id], 
                [DESC]
            FROM #test t1

最後に、データに PIVOT テーブルを作成します (その演算子を "偽造" する標準的な SQL 2000 の方法で行います)。次に、その「PIVOT テーブル」を、必要な列のみを返す派生 select に配置しますが、code 列と rownum 列で並べ替えて、要求した出力を生成できます。

     SELECT Code,[type-1],[type-2],[type-3],[type-4]
        FROM (Select P.Code,RowNum
                   , Min( Case When type = '1' Then [DESC] End ) As [type-1]
                   , Min( Case When type = '2' Then [DESC] End ) As [type-2]
                   , Min( Case When type = '3' Then [DESC] End ) As [type-3]
                   , Min( Case When type = '4' Then [DESC] End ) As [type-4]
                      From #Numbered As P
                        Group By P.Code,RowNum) R
        ORDER BY Code,RowNum

これについてさらに説明が必要な場合はお知らせください。

于 2011-12-25T09:12:49.403 に答える
0
Select t1.code, t1.description, t2.description, t3.description from
(Select code, description from table where type=1) t1, 
(Select code, description from table where type=2) t2, 
(Select code, description from table where type=3) t3,
(Select code, description from table where type=4) t4
Where t1.code=t2.code and t2.code=t3.code and t3.code=t4.code and t4.code=t1.code
and t4.code=t2.code and t1.code=t3.code

このクエリを試してみてください。null は返されませんが、繰り返される値が返されます

ご不明な点がございましたらお問い合わせください

于 2011-12-25T09:03:17.877 に答える