如何查询以下SQL Server表?

时间:2018-01-24 11:47:24

标签: mysql sql sql-server

我的表格如下:

MY TABLE

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

我的结果应该是:

RESULT TABLE

ID   OLDFREQUENCY   NEWFREQUENCY
123   YEARLY        HALFYEARLY
256    QUARTERLY     HALFYEARLY
456    QUARTERLY     YEARLY

我正在使用SQL Server。

2 个答案:

答案 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更改为实际的表名。