我在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
答案 0 :(得分: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)
答案 1 :(得分: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的安装脚本)