Я не уверен, как SQL может упорядочить следующий запрос. Обратите внимание на РЕДАКТИРОВАТЬ ниже.
Вот как выглядят 3 таблицы:
Root:
ID AuditID R1 R2 R3
1 1 Key1 Text1 20
Узел:
ID NodeID N1 N2 N3
1 1 30 40 Text2
1 2 35 45 Text3
Лист:
ID NodeID Metric Value
1 1 L1 50
1 1 L2 60
1 1 L3 70
1 2 L1 80
1 2 L2 90
1 2 L3 100
Я хочу, чтобы мой вывод выглядел в следующем порядке:
name val
R1 Key1
R2 Text1
R3 20
N1 30
N2 40
N3 Text2
N1 35
N2 45
N3 Text3
L1 50
L2 60
L3 70
L1 80
L2 90
L3 100
Я использовал следующий код, чтобы получить этот формат:
select name, val from(
Select convert(nvarchar(max), runpvt.name) as name, runpvt.val from
(select convert(nvarchar(max), R1) as R1,
convert(nvarchar(max), R2) as R2,
convert(nvarchar(max), R3) as R3 from
root
) root
UNPIVOT
(val for name in ([R1], [R2], [R3])) as runpvt
union all
select name, val from(
select convert(nvarchar(max), nunpvt.name) as name, nunpvt.val from
(select ROW_NUMBER() OVER(ORDER BY ID ASC) AS Row#,
convert(nvarchar(max), N1) as N1,
convert(nvarchar(max), N2) as N2,
convert(nvarchar(max), N3) as N3 from
node) node
UNPIVOT
(val for name in (N1, N2, N3)) as nunpvt)tbl1
union all
select name, val from (
select convert(nvarchar(max), l.Metric) as name, convert(nvarchar(max), l.Value) as val,
ROW_NUMBER() OVER (ORDER BY ID ASC) as ROW## from leaf as l)tbl2
)dtbsvalues
Обеспечивает ли заказ row_number
то, что я всегда получу требуемый заказ?
ОБРАТИТЕ ВНИМАНИЕ ИЗМЕНИТЬ: Я добавил следующий код. Могу ли я быть уверен, что N1, N2, N3 будут из 1-го ряда, а затем N1, N2, N3 из 2-го ряда и так далее?
Declare @leaf as int
Set @leaf = (SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_catalog = 'trial'
AND table_name = 'root')
Declare @node as int
Set @node = (SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_catalog = 'trial'
AND table_name = 'node')
select name, val from(
Select convert(nvarchar(max), runpvt.name) as name, runpvt.val, 1 as rid, 1 as filter from
(select convert(nvarchar(max), R1) as R1,
convert(nvarchar(max), R2) as R2,
convert(nvarchar(max), R3) as R3 from
root
) root
UNPIVOT
(val for name in ([R1], [R2], [R3])) as runpvt
union all
select name, val, rid, 1+@leaf as filter from(
select convert(nvarchar(max), nunpvt.name) as name, nunpvt.val, rid from
(select ROW_NUMBER() OVER (ORDER BY ID ASC) as rid ,
convert(nvarchar(max), N1) as N1,
convert(nvarchar(max), N2) as N2,
convert(nvarchar(max), N3) as N3 from
node) node
UNPIVOT
(val for name in (N1, N2, N3)) as nunpvt)tbl1
union all
select name, val, rid, 1+@node+@leaf as filter from (
select convert(nvarchar(max), l.Metric) as name, convert(nvarchar(max), l.Value) as val,
ROW_NUMBER() OVER (ORDER BY ID ASC) as rid from leaf l)tbl2
)dtbsvalues
order by filter, rid