plsql高级或条件

plsql advanced or condition

我有一个 table 包含 post 个地址。 我的查询如下所示:

SELECT "ID", postcode, numbertype, minnumber, maxnumber
INTO huidigPostcodeID_FK, databasePostcode, databaseNumberType, databaseMinNumber, databaseMaxNumber
FROM POSTCODE 
WHERE POSTCODE_ID = 79417568 AND (NUMBERTYPE = 'odd' OR NUMBERTYPE = 'mixed')

在大多数情况下,这工作正常,因为它只需要提供 1 行。 在有 2 个相同记录的情况下(一个 numbertype = odd,另一个混合) 查询 returns 2 行。

        ID POSTCODE NUMBERTYPE  MINNUMBER  MAXNUMBER
---------- -------- ---------- ---------- ----------
    395755 7941KD   odd                 9          9 
    395756 7941KD   mixed               1         22 

我不想要这个,因为我得到了一个错误。有人有解决方案,其中程序只获得一个 numbertype = 'mixed' 的记录吗?

所以在上面的例子中,我只希望这条记录不显示:

    ID POSTCODE NUMBERTYPE  MINNUMBER  MAXNUMBER

395756 7941KD   mixed               1         22 

您可以通过聚合来做到这一点。但不清楚你到底想要什么。类似于:

SELECT min(id), postcode,
       (case when min(numbertype) = max(numbertype) then min(numbertype)
             else 'mixed'
        end)
       min(minnumber), max(maxnumber)
INTO huidigPostcodeID_FK, databasePostcode, databaseNumberType, databaseMinNumber, databaseMaxNumber
FROM POSTCODE 
WHERE POSTCODE_ID = 79417568 AND (NUMBERTYPE = 'odd' OR NUMBERTYPE = 'mixed')
GROUP BY postcode

我认为也可以使用 window 函数来完成此操作:

SELECT "ID", postcode, numbertype, minnumber, maxnumber
  INTO huidigPostcodeID_FK, databasePostcode, databaseNumberType, databaseMinNumber, databaseMaxNumber
  FROM (
    SELECT "ID", postcode, numbertype, minnumber, maxnumber
         , ROW_NUMBER() OVER ( PARTITION BY postcode ORDER BY DECODE(numbertype, 'mixed', 0, 1) ) AS rn
      FROM postcode
     WHERE postcode_id = 79417568 AND (numbertype = 'odd' OR numbertype = 'mixed')
) WHERE rn = 1

在这种情况下,如果 postcode 的给定值有两条记录,它将 select numbertype 的值为 'mixed' 的记录。人们也可以简单地在 OVER( ) 子句中使用 ORDER BY numbertype 但这并没有明确地说 'mixed' 应该放在第一位。

希望对您有所帮助。