在 SELECT 中选择行作为列

2022-01-22 00:00:00 pivot sql tsql sql-server

可能重复:
如何选择列作为行?

我有一张带有 ID 的表格,例如

I have a table with ID's, like

Table
-------
  1
  2
  3
  4
  5
  and so on

我有这个问题,

SELECT A,B,这里我需要选择 Id 作为列,FROM MyTable

SELECT A,B,Here I need To SELECT the Id's as Column, FROM MyTable

所以结果是,

  A  B  1  2  3  4  5  6  7 and so on
  -----------------------------------

推荐答案

你想要一个交叉表查询.看看这个:http://www.simple-talk.com/sql/t-sql-programming/creating-cross-tab-queries-and-pivot-tables-in-sql/

You want a cross tab query. Check this out: http://www.simple-talk.com/sql/t-sql-programming/creating-cross-tab-queries-and-pivot-tables-in-sql/

它解释了如何做一个简单的交叉表查询,这可能就是你所需要的.但是,您似乎也可以从作者创建的存储过程中受益,以克服交叉表查询的一些缺点.

It explains how to do a simple cross tab query which may be all you need. However, it looks like you may also benefit from the stored procedure the writer created to overcome some shortcomings of the cross tab query.

相关文章