0

我有一张如下表

OP    OP_var    SPS    SPS_sq
1010    01    KEB_x    01
1010    01    KEK_x    02
1010    02    KEH_c    01
1010    02    KEK_y    02
1010    02    KEB_d    03
1020    01    KEK_f    01
1020    01    KEE_g    02

OP 列具有方差 (OP_var),其中包含一组 SPS。SPS_sq 是这些 SPS 行在OP+OP_var.

我想显示 KEK%,其中 KEK% 的 SPS_sq 不是最后一个(意思是,只要不是最后一个,KEK% 就是 OP 和 OP_var 的序列号的第一个或中间的任何位置。

输出应如下所示:

OP     OP_var     SPS     SPS_sq
1010     02       KEK_y    02
1020     01       KEK_f    01     

忽略. KEK%_OP+OP_var

4

2 回答 2

0

I assume you're looking for a random row per (op, op_var) combination. The random row has to have an SPS like 'KEK%', and it cannot have the same SPS as the last row. (That implies it cannot be the last row itself.)

This example uses window functions, which are available in SQL Server, Oracle, PostGRES. It uses a SQL Server specific way (newid()) to create a random order.

select  *
from    (
        select  row_number() over (
                    partition by yt1.OP, yt1.OP_var
                    order by newid()) as rn2 -- Random order
        ,       yt1.*
        from    dbo.YourTable yt1
        join    (
                select  row_number() over (
                            partition by OP, OP_var
                            order by SPS_sq desc) as rn
                ,       *
                from    YourTable
                ) as last_row
        on      yt1.OP = last_row.OP
                and yt1.OP_var = last_row.OP_var
                and last_row.rn = 1 -- Highest SPS_sq
        where   yt1.SPS <> last_row.SPS
                and yt1.SPS like 'KEK%'
        ) SubQueryALias
where   rn2 = 1 -- Random KEK row that doesn't share SPS with last row

Example at SQL Fiddle.

于 2013-05-22T10:12:28.953 回答
0

如果您想要所有kek,其中kek 不是(op,op_var)的最大sps_sq

select * from Table1 t
where t.sps like 'KEK%' 
and not exists
(select null from Table1 t1
inner join (select MAX(t2.sps_sq) as maxsps_sq, t2.op, t2.op_var 
            from Table1 t2
            GROUP BY t2.op, t2.op_var) as getmax
on t1.op = getmax.op and t1.op_var = getmax.op_var 
 and t1.sps_sq = getmax.maxsps_sq
where t1.op = t.op and t1.op_var = t.op_var and t1.sps = t.sps and t.sps_sq = t1.sps_sq
);

SqlFiddle

注意:正如 Andomar 所注意到的,这将占用没有最后一个 sps_sq 编号的 [op, op_var] 的所有 kek%。

于 2013-05-22T10:00:52.420 回答