比较两个具有相同键的行,并确定值是否不同

时间:2018-08-24 09:59:07

标签: sql oracle

我有一个看起来像这样的表:

+ -------------+------------+------+-----------+-----------+
| M_PACK_INTID | M_PACK_REF | M_NB | M_XPFWSPT | M_BPFOLIO |
+ -------------+------------+------+-----------+-----------+
| 1.781        | 100        | 101  | 12        | PFOLIO    |
| 1.781        | 100        | 102  | 12        | PFOLIO    |
| 1.781        | 100        | 103  | 12        | PFOLIO    |
| 1.781        | 100        | 104  | 12.3      | PFOLIO    |
| 1.781        | 200        | 201  | 15        | PFOLIO    |
| 1.781        | 200        | 202  | 15        | PFOLIO    |
| 1.781        | 200        | 203  | 15        | PFOLIO    |
| 1.781        | 200        | 204  | 15        | PFOLIO    |
+ -------------+------------+------+-----------+-----------+

基本上,每个M_PACK_REF都有4个不同的M_NB,并为其分配了可能不同的M_XPFWSPT

期望的结果:我想提取所有第一第四 M_PACK_REF的{​​{1}} }的值为M_NB。 在上面的示例中,M_XPFWSPT就是这种情况(因为其M_PACK_REF = 100具有M_NB = 101,而M_XPFWSPT = 12具有M_NB = 104)。

这是一个SQL fiddle,您可以在其中玩耍。

根据此小提琴中的数据,预期结果将是这样的:

M_XPFWSPT = 12.3

我尝试从该表中提取每个M_PACK_REF 100 400 的第一行和最后一行,并计算M_PACK_REF的发生率,这些发生率是不同的:

M_XPFWSPT

...但是它显示了一个空表。 谁能帮忙吗?

3 个答案:

答案 0 :(得分:2)

首先对行进行编号,因此请按M_PACK_REF获取第一和第四行。然后比较。

with numbered as
(
  select
    m_pack_ref,
    m_nb,
    m_xpfwspt,
    row_number() over (partition by m_pack_ref order by m_nb) as rn
  from gather
)
select *
from (select * from numbered where rn = 1) first
join (select * from numbered where rn = 4) fourth
  on  fourth.m_pack_ref = first.m_pack_ref
  and fourth.m_xpfwspt <> first.m_xpfwspt;

答案 1 :(得分:2)

如果我理解正确,您可以使用existshaving来制作。

select M_PACK_REF, M_NB, M_XPFWSPT
from GATHER g1
WHERE exists (
  SELECT 1 
  FROM GATHER g2
  HAVING
      min(g2.M_NB) = g1.M_NB OR MAX(g2.M_NB) = g1.M_NB 
  and 
      COUNT(distinct M_XPFWSPT) > 1
)

答案 2 :(得分:1)

您可以尝试这个吗?

WITH filtered as 
(
SELECT 
    M_PACK_REF,
    M_XPFWSPT,
    COUNT(*) as Cnt
FROM GATHER
    WHERE M_NB like '%01' or M_NB like '%04'
GROUP BY M_PACK_REF, M_XPFWSPT
HAVING COUNT(*) = 1
)

SELECT DISTINCT M_PACK_REF FROM filtered

这样的想法是,如果M_XPFWSPT的值不同,则每对M_PACK_REF,M_XPFWSPT将只有一行。如果M_XPFWSPT相同-count(*)将返回2