【问题标题】:How can I get data in rows and columns order如何按行和列的顺序获取数据
【发布时间】:2015-11-24 11:06:14
【问题描述】:

我有一个包含 8 行的表 像 1001 1002 1003 1003 1004 1005 1006 1007 1008 从这些我想将记录显示为 4 列 *2 行

1001 1002 1003 1004

1005 1006 1007 1008

我怎样才能得到这个? 请帮助我

【问题讨论】:

  • 使用 ROW_NUMBER 和模数,如果除以四增加一个变量后有提示,按该变量分组。至于sql server中的GROUP_CONCAT,这是一个很常见的问题
  • 表格!=电子表格。你在这里开始了一条黑暗的道路。最好在 presentation 层做这样的 presentation 逻辑,而不是在数据库的深处。

标签: sql-server


【解决方案1】:

对于您的确切问题,您可以轻松地执行以下操作:

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 开始。这取决于。

但我敢打赌,这不是您需要选择的唯一内容,但对于您的问题,这里是答案:-)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2021-09-10
    • 2019-09-10
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多