2

我在 SQL 中有一个这样的表(它不是按顺序排列的)

A B         VAL                  VAL2
---------------------------------------------   
1 1 -2.1846000000000e+02  0.0000000000000e+00
2 2 -2.1846000000000e+02  0.0000000000000e+00
3 2  6.4000000000000e+01  0.0000000000000e+00
1 2  6.4000000000000e+01  0.0000000000000e+00
2 3  6.4000000000000e+01  0.0000000000000e+00
3 3 -2.1846000000000e+02  0.0000000000000e+00
3 1  6.4000000000000e+01  0.0000000000000e+00
2 1  6.4000000000000e+01  0.0000000000000e+00
1 3  6.4000000000000e+01  0.0000000000000e+00

所以每个元组 A,B 代表矩阵的一个点我怎样才能将它转换成一个实际的矩阵,比如

A1                      A2                      A3
--------------------------------------------------------------------
-2.1846000000000e+02    6.4000000000000e+01     6.4000000000000e+01
6.4000000000000e+01     -2.1846000000000e+02    6.4000000000000e+01
6.4000000000000e+01     6.4000000000000e+01    -2.1846000000000e+02 
4

2 回答 2

4

这可以使用如下查询来完成:

select
  max(case when B = 1 then VAL end) as A1,
  max(case when B = 2 then VAL end) as A2,
  max(case when B = 3 then VAL end) as A3
from
  MatrixData D
group by
  A;

要生成任意大小的矩阵,您需要动态生成的 SQL 代码,如下所示:

declare @sql varchar(5000)

select @sql = coalesce(@sql + ',' + char(13) + char(10), '') +
  'max(case when B = ' + cast(B as varchar(10))
    + ' then VAL end) as A' + cast(B as varchar(10))
from
  MatrixData D
group by
  B

set @sql =
  'select
    ' + @sql + '
  from
    MatrixData D
  group by
    A;'
exec(@sql)

演示:http ://www.sqlfiddle.com/#!3/7ee1e/13

于 2012-04-25T18:27:09.047 回答
3

给定表 M (x, y, v)

SELECT x, [1], [2], [3], [4], ...
FROM
(SELECT x, y, v FROM M) AS s
PIVOT
(
min(v)
FOR y IN ([1], [2], [3], [4], ...)
) AS pvt
order by x

, ...表示根据需要继续该系列,但不要将其留在脚本中

演示:http ://www.sqlfiddle.com/#!3/7ee1e/ 17(感谢 mellamokb 的设置脚本)

于 2012-04-25T18:28:16.947 回答