我有一个包含8行的表 喜欢 1001 1002 1003 1003 1004 1005 1006 1007 1008 从这些我想将记录显示为4列* 2行
1001 1002 1003 1004
1005 1006 1007 1008
我怎么能得到这个? 请帮助我
答案 0 :(得分:0)
对于您的确切问题,您可以轻松地执行以下操作:
declare @t as table(
[column] int
)
insert into @t
select '1001' union all
select '1002' union all
select '1003' union all
select '1004' union all
select '1005' union all
select '1006' union all
select '1007' union all
select '1008'
select
[MyColumn1] = (select top 1 T.[column] from @t AS T where [T].[column] = '1001'),
[MyColumn2] = (select top 1 T.[column] from @t AS T where [T].[column] = '1002'),
[MyColumn3] = (select top 1 T.[column] from @t AS T where [T].[column] = '1003'),
[MyColumn4] = (select top 1 T.[column] from @t AS T where [T].[column] = '1004')
union all
select
[MyColumn1] = (select top 1 T.[column] from @t AS T where [T].[column] = '1005'),
[MyColumn2] = (select top 1 T.[column] from @t AS T where [T].[column] = '1006'),
[MyColumn3] = (select top 1 T.[column] from @t AS T where [T].[column] = '1007'),
[MyColumn4] = (select top 1 T.[column] from @t AS T where [T].[column] = '1008')
或者您可以使用Pivot
输出将如此:
+------+------+------+------+
| 1001 | 1002 | 1003 | 1004 |
+------+------+------+------+
| 1005 | 1006 | 1007 | 1008 |
+------+------+------+------+
如果它按照确切的顺序排列,您可以使用while循环执行动态查询,并将整数变量递增+1,从1001开始。这取决于。
但我敢打赌,这不是你唯一需要选择的东西,但对于你的问题,这里的答案是: - )