我的表格如下:
ID SEQNO FREQUENCY
123 0 YEARLY
123 1 HALFYEARLY
256 0 QUARTERLY
256 1 YEARLY
256 2 HALFYEARLY
456 0 QUARTERLY
456 1 YEARLY
456 2 YEARLY
我的结果应该是:
ID OLDFREQUENCY NEWFREQUENCY
123 YEARLY HALFYEARLY
256 QUARTERLY HALFYEARLY
456 QUARTERLY YEARLY
我正在使用SQL Server。
答案 0 :(得分:0)
尝试此查询
SELECT FQ1.ID, FQ1.FREQUENCY as OLDFREQUENCY, FQ2.FREQUENCY as NEWFREQUENCY
from FREQUENCIES FQ1 inner join FREQUENCIES FQ2
ON FQ1.ID = FQ2.ID
WHERE FQ1.SEQNO = 0 OR FQ2.SEQNO = 1;
请告诉我它是否有效。
答案 1 :(得分:0)
试试这段代码:
select id,
max(case when seqcnt = -1 then frequency end) [oldfrequency],
max(case when seqcnt = 1 then frequency end) [newfrequency]
from (
--this subquery will create new column named seqCnt, which will be equal to:
-- -1 when this is the first seqno
-- 1 if this is the last seqno
-- 0 in other cases
select *, case when max(seqno) over (partition by id) = seqno then 1 else case when seqno = 0 then -1 else 0 end end [seqCnt] from @x
) as a
-- we only want first or last seqno
where seqcnt in (-1, 1)
group by id
请注意,您必须将@x
更改为实际的表名。