繁体   English   中英

通过变量获取第一行号

[英]Get the first rownumber by variable

我有下面的代码,我想拉表中的第一个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”时出现错误。

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

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-zh/with.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM