首先,我运行此查询,创建一个表并插入两行数据。
declare @data table (date varchar(10),x1 int,x2 int,x3 int,y1 int,y2 int,y3 int,z1 numeric(5,2),z2 numeric(5,2),z3 numeric(5,2))
insert into @data values ('2017-05-15',11,12,15,21,31,41,0.1,0.4,0.5)
insert into @data values ('2017-05-16',11,12,15,21,31,41,0.1,0.4,0.5)
然后我运行此查询来转换表中的行:
select date,x1 as 'a1',y1 as 'b1', z1 as 'c1' from @data
union all
select date,x2 as 'a2',y2 as 'b2', z2 as 'c2' from @data
union all
select date,x3 as 'a3',y3 as 'b3', z3 as 'c3' from @data
order by date
我得到了这个结果
2017-05-15 11 21 0.10
2017-05-15 12 31 0.40
2017-05-15 15 41 0.50
2017-05-16 15 41 0.50
2017-05-16 12 31 0.40
2017-05-16 11 21 0.10
第一个表(前3行)正在生成OK,第二个表正在反转。然后第3个也好了等等......
请尝试运行此查询以了解我的意思。
KBV。
答案 0 :(得分:1)
我认为您正在尝试显示存储为行的3x3矩阵。如果是这种情况,那么您可以在每个矩阵行中添加一个硬编码的数字,并在日期之后按该数字排序:
select 1 as ordernumber, date,x1 as 'a1',y1 as 'b1', z1 as 'c1' from @data
union all
select 2 as ordernumber, date,x2 as 'a2',y2 as 'b2', z2 as 'c2' from @data
union all
select 3 as ordernumber, date,x3 as 'a3',y3 as 'b3', z3 as 'c3' from @data
order by date, ordernumber
如果您不想显示该号码,请使用子查询:
SELECT
date,
a1,
b1,
c1
FROM
(
select 1 as ordernumber, date,x1 as 'a1',y1 as 'b1', z1 as 'c1' from @data
union all
select 2 as ordernumber, date,x2 as 'a2',y2 as 'b2', z2 as 'c2' from @data
union all
select 3 as ordernumber, date,x3 as 'a3',y3 as 'b3', z3 as 'c3' from @data
) AS T
order by
date,
ordernumber