我有以下的旋转表,我设法做了,这是结果,我想进一步。
RID; NTRITCode; NTRIId; Parameter; Usage; Rate**
1; CURRENT; 4; Peak; 100; 0.1
1; CURRENT; 4; NonPeak; 200; 0.2
1; PROPOSED; 6; Peak; 100; 0.2
1; PROPOSED; 6; NonPeak; 200; 0.3
1; PROPOSED; 8; Peak; 200; 0.3
1; PROPOSED; 8; NonPeak; 200; 0.5
如您所见,有2套建议(ID = 6和8)。我想以某种方式显示如下,所以每组都有一对CURRENT以及PROPOSED如下:
**Sequence; RID; NTRITCode; NTRIId; Parameter; Usage; Rate**
1; 1; CURRENT; 4; Peak; 100; 0.1
1; 1; CURRENT; 4; NonPeak; 200; 0.2
1; 1; PROPOSED; 6; Peak; 100; 0.2
1; 1; PROPOSED; 6; NonPeak; 200; 0.3
2; 1; CURRENT; 4; Peak; 100; 0.1
2; 1; CURRENT; 4; NonPeak; 200; 0.2
2; 1; PROPOSED; 8; Peak; 200; 0.3
2; 1; PROPOSED; 8; NonPeak; 200; 0.5
我能想到的只是使用CURSOR和UNION的组合,但有没有可以做到这一点的TSQL?
由于
答案 0 :(得分:1)
SQL: how to get all the distinct characters in a column, across all rows
答案 1 :(得分:1)
我不确定你是否真的需要递归查询和Numbers / Tally表一样,以便为“CURRENT”值获取与“PROPOSED”值相同的序列号。
With
Numbers As
(
Select Row_Number() Over ( Order By C1.object_id ) As Value
From sys.columns As C1
Cross Join sys.columns As C2
)
, ProposedSequences As
(
Select NTRIId
, Row_Number() Over ( Order By NTRIId ) As Sequence
From Table
Where NTRITCode = 'PROPOSED'
Group By NTRIId
)
, CurrentSequences As
(
Select RID, NTRITCode, NTRIId, Parameter, Usage, Rate
, Numbers.Value As Sequence
From Table
Cross Join Numbers
Where NTRITCode = 'Current'
And Numbers.Value <= (Select Max(Sequence) From ProposedSequence)
)
Select Sequence, RID, NTRITCode, NTRIId, Parameter, Usage, Rate
From CurrentSequences
Union All
Select PS.Sequence, T.RID, T.NTRITCode, T.NTRIId, T.Parameter, T.Usage, T.Rate
From ProposedSequences As PS
Join Table As T
On T.NTRIId = PS.NTRIId
Order By PS.Sequence, T.NTRITCode
答案 2 :(得分:1)
select row_number() over(PARTITION by c.NTRITCode,c.parameter order by c.NTRITCode, c.ntriid,c.parameter) nb,
c.* from table c
join (select * from table where NTRITCode='PROPOSED') p
on c.rid=p.rid and c.parameter=p.parameter
and not(p.NTRIId=c.NTRIId and c.parameter=p.parameter)
order by nb, c.ntriid, c.parameter desc