0

これがテーブル構造とサンプルデータです

create table #tmp ( Id int, Name varchar(100))
insert into #tmp (Id,Name)
Values (1,'Add')
insert into #tmp (Id,Name)
Values (2,'Update')

insert into #tmp (Id,Name)
Values (3,'Delete')

期待される結果は次のようになります。

Add  Update  Delete
===  ======  ======
1    2       3
4

2 に答える 2

2

データを行から列に変換する方法はいくつかあります。

データベースにPIVOT関数がある場合は、次のコードを使用してデータをピボットできます。

select [Add], [Update], [Delete]
from
(
  select id, name
  from #tmp
) src
pivot
(
  max(id)
  for name in ([Add], [Update], [Delete])
) piv

SQL FiddlewithDemoを参照してください。

CASEまたは、次の式で集計関数を使用できます。

select 
  max(case when name = 'Add' then id end) [Add],
  max(case when name = 'Update' then id end) [Update],
  max(case when name = 'Delete' then id end) [Delete]
from #tmp

SQL FiddlewithDemoを参照してください

于 2013-03-22T11:06:01.783 に答える
2

してみてください:

SELECT [Add], [Update], [Delete]
    FROM (select * from #tmp) up 
        PIVOT (sum(id) FOR Name IN ([Add], [Update], [Delete])) AS pvt
于 2013-03-22T11:06:18.723 に答える