SQL将结果拆分为一行

时间:2014-07-15 18:18:21

标签: sql sql-server pivot

我无法理解如何将SQL结果拆分为一行。 让我们说我有一个问题:

select Titles, Values from myTable

用restult:

|  TitlesHeader   |   ValuesHeader  |
|title1           |value1           |
|title2           |value2           |
|title3           |value3           |

我需要一行

|Title1Header | Value1Header | Title2Header | Value2Header | Title3Header | Values3Header|
|title1       |value1        |title2        |value2        |tilte3        | value3       |

我们假设我知道行数。但总的来说,有可能动态生成? 或者例如,目前我知道有5行,我需要将其拆分为一行,但我知道将来它不会增长超过10,并且填充哪些不存在空值或0。

提前致谢!!!

1 个答案:

答案 0 :(得分:0)

试试这个:

简单版

SQL小提琴:http://sqlfiddle.com/#!6/67446/3

with cte (r, t, v) as (
  select row_number() over (order by [title], [value]) r
  , [title]
  , [value]
  from myTable
)
select x1.t title1header
, x1.v value1header
, x2.t title2header
, x2.v value2header
, x3.t title3header
, x3.v value3header
from cte x1
inner join cte x2 on x2.r = 2
inner join cte x3 on x3.r = 3
where x1.r = 1

动态SQL版

自动处理对行数的更改,但不是很好。 SQL小提琴:http://sqlfiddle.com/#!6/2afca/11

declare @sql nvarchar(max)
, @i bigint = 1
select @sql = coalesce(@sql + ',','select ')
+ coalesce(quotename([title],''''),'null') 
+ ' Title' + cast(@i as nvarchar) + 'Header'
+ ','
+ coalesce(quotename([value],''''),'null')
+ ' Value' + cast(@i as nvarchar) + 'Header'
, @i = @i + 1
from myTable
order by [title]

exec (@sql)

数据透视表版本

(非常可怕/不推荐)

SQL小提琴:http://sqlfiddle.com/#!6/67446/1

select 
  max([t1]) title1header
, max([v1]) value1header
, max([t2]) title2header
, max([v2]) value2header
, max([t3]) title3header
, max([v3]) value3header
from (
  select 1 y
  , 't' + cast(row_number() over (order by [title], [value]) as nvarchar) tr
  , 'v' + cast(row_number() over (order by [title], [value]) as nvarchar) vr
  , [title]
  , [value]
  from myTable
) x
pivot
(
  max([title]) for tr in ([t1], [t2], [t3])
) p1
pivot
(
  max([value]) for vr in ([v1], [v2], [v3])
) p2
group by y