SQL语句的where子句中的条件语句

时间:2016-06-15 20:22:24

标签: sql oracle

我正在运行一个相当复杂的SQL查询,该查询从Oracle数据库中访问多个表。我试图从一个有两个关键列的新表中引入数据,看起来像这样:

function sendSMS($from, $message, $time, $to){
    $objGsm = new COM("AxSms.Gsm", NULL, CP_UTF8 );
    $objGsm->LogFile = sys_get_temp_dir()."Gsm.log"; 
    //Windows default: 'C:\Windows\Temp\Gsm.log'

    //Form submitted

    $obj;
    $strMessageReference;
    $objSmsMessage   = new COM("AxSms.Message",    NULL, CP_UTF8 );
    $objSmsConstants = new COM("AxSms.Constants" , NULL, CP_UTF8 );

    $strName = 'Modem';
    $strPincode = '';
    $strRecipient = '$number';
    $iDeviceSpeed = '0';

    $objGsm->Clear();
    $objGsm->LogFile = '';
    $objGsm->Open($strName, $strPincode, $iDeviceSpeed);

    if ($objGsm->LastError != 0){
        $strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);
        $objGsm->Close();
    }
    else{
        //Message Settings
        $objSmsMessage->Clear();
        $objSmsMessage->ToAddress = $to;
        $objSmsMessage->Body = $message;

        $objSmsMessage->DataCoding = $objSmsConstants->DATACODING_UNICODE;

        //Send the message !
        $obj = $objSmsMessage;
        $objGsm->SendSms($obj, $objSmsConstants->MULTIPART_ACCEPT, 0);
        $objSmsMessage = $obj;

        $strResult = $objGsm->LastError . ": " . $objGsm->GetErrorDescription($objGsm->LastError);

        $objGsm->Close();
    }
}

每个唯一的key1值都有一个NULL key2记录,如果key2不存在,则该记录应该是默认值。我目前的疑问是:

key1  key2  date
001         2016-06-12
001   0001  2016-06-13
002         2016-06-14
003         2016-06-15
003   0001  2016-06-16
...

这给了我newtable中的所有内容,但我需要每个key1值的唯一记录。我希望查询返回非NULL key2记录的日期(如果有),否则返回NULL key2记录的日期。

我很感激你的帮助。

1 个答案:

答案 0 :(得分:1)

Oracle提供KEEP FIRST从列表的“最佳”记录中选择一个值。你想要最好的唱片日期。您可以在子查询中使用KEEP FIRST获取它:

SELECT 
  <columns from other tables>,
  (
    select max(n.date) keep (dense_rank first order by n.key2 nulls last)
    from newtable n
    where n.key1 = k.key1
     and (n.key2 = k.key2 OR n.key2 is null)
  ) as newtable_date
FROM keytable k
JOIN <other database tables>
WHERE ...