通过变量获取第一行号

时间:2019-04-04 17:36:20

标签: sql

我有如下代码,我想提取表中的第一个rownu = 1,但是当我在where语句中编写它时,我得到了一个错误:

SELECT 
    * 
FROM 
    (SELECT  
         VID,
         SPRTELE_PHONE_NUMBER AS Phone,
         ROW_NUMBER() OVER (PARTITION BY VID ORDER BY SPRTELE_TELE_cODE desc) AS ROWNU         
     FROM 
         PERSONNEL_VIEW, SPRTELE 
     WHERE     
         SPRTELE_PIDM = PIDM   
         AND (SPRTELE_SEQNO = (SELECT MAX (SPRTELE_SEQNO)
                               FROM SPRTELE
                               WHERE SPRTELE_PIDM = PIDM)))
    ) DATA
WHERE 
    DATA.ROWNU = 1

UNION

SELECT
    *  
FROM
    (SELECT 
         VID,
         SPRTELE_PHONE_NUMBER AS Phone,
         '1' AS ROWNU
     FROM 
         STUDENT_VIEW, SPRTELE
     WHERE     
         SPRTELE_PIDM = PIDM  
         AND (SPRTELE_SEQNO = (SELECT MAX (SPRTELE_SEQNO)
                               FROM SPRTELE
                               WHERE SPRTELE_PIDM = PIDM))
         AND TERM_CODE = '201920'
    ) DATA
WHERE
    data.rownu = 1;

输出类似于

VID           PHONE    ROWNU
-----------------------------
VI1003365     5891449     1
VI2380659     4932389     1
VI2997998     6371006     1 
VI2997998     5821347     2

我只需要拉rownu=1,但是当我在代码中放入“ rownu = 1”时会出现错误。

1 个答案:

答案 0 :(得分:1)

您将需要为此创建一个子查询:

SELECT * 
FROM (
  SELECT vid, 
   sprtele_phone_number                 AS Phone, 
   Row_number() 
     OVER ( 
       partition BY vid 
       ORDER BY sprtele_tele_code DESC) AS ROWNU 
   FROM   personnel_view, 
       sprtele 
   WHERE  sprtele_pidm = pidm 
       AND ( sprtele_seqno = (SELECT Max (sprtele_seqno) 
                              FROM   sprtele 
                              WHERE  sprtele_pidm = pidm) )
) DATA
WHERE DATA.ROWNU =1; 

您可以在这里了解原因:https://www.sqltheater.com/blog/cant-use-row-number-where/

-编辑-

如果查询变得更复杂,则可以使用WITH子句:

WITH UNION_DATA AS ( 
  SELECT  VID,
          SPRTELE_PHONE_NUMBER    AS Phone,
          ROW_NUMBER()
          OVER (
             PARTITION BY VID 
             ORDER BY SPRTELE_TELE_cODE desc)  AS ROWNU         
  FROM PERSONNEL_VIEW ,  SPRTELE 
  WHERE     SPRTELE_PIDM = PIDM   
        AND (SPRTELE_SEQNO =
            (SELECT MAX (SPRTELE_SEQNO)
               FROM SPRTELE
                  WHERE SPRTELE_PIDM = PIDM ))
  UNION
  SELECT VID,
      SPRTELE_PHONE_NUMBER    AS Phone,
      '1'  AS ROWNU
  FROM STUDENT_VIEW, SPRTELE
  WHERE     SPRTELE_PIDM = PIDM  
       AND (SPRTELE_SEQNO =
            (SELECT MAX (SPRTELE_SEQNO)
               FROM SPRTELE
              WHERE SPRTELE_PIDM = PIDM ))
       AND TERM_CODE = '201920')
SELECT *
FROM UNION_DATA UD 
WHERE UD.ROWNU = 1

详细了解WITH子句:https://docs.oracle.com/cd/E17952_01/mysql-8.0-en/with.html