Selecting Distinct field and row num just to display an id number gives duplicated data

前端 未结 3 1151
孤城傲影
孤城傲影 2021-01-27 06:07

I have a table application and it has 10 columns. category is one column and this column has duplicated values. To get distinct values I have a query

SELECT distinc

相关标签:
3条回答
  • 2021-01-27 06:48

    please use

    SELECT CATEGORY as CategoryName, sum(rownum) FROM APPLICATION WHERE applicationId=? GROUP BY CATEGORY
    
    0 讨论(0)
  • 2021-01-27 06:58

    You need to use the subquery as follows:

    select CategoryName , rownum as categoryId from
    (SELECT distinct(CATEGORY) as CategoryName FROM APPLICATION where applicationId=?)
    

    You can also use the analytical function as follows:

    SELECT distinct(CATEGORY) as CategoryName, 
           rank() over (order by CATEGORY) as categoryId 
      FROM APPLICATION where applicationId=?
    

    Example:

    I have the following data:

    SQL> SELECT WRITER_ID, TWEET FROM TWEET;
    
     WRITER_ID TWEET
    ---------- -----
             1 T1
             1 T2
    
    SQL>
    

    See the output of both of the above query:

    SQL> SELECT WRITER_ID, ROWNUM AS GENERATED_NUMBER FROM
      2  (SELECT DISTINCT WRITER_ID AS WRITER_ID FROM TWEET);
    
     WRITER_ID GENERATED_NUMBER
    ---------- ----------------
             1                1
    
    SQL> SELECT DISTINCT ( WRITER_ID ),
      2                  RANK() OVER(ORDER BY WRITER_ID) AS GENERATED_NUMBER
      3    FROM TWEET;
    
     WRITER_ID GENERATED_NUMBER
    ---------- ----------------
             1                1
    

    Now, Let me change my data

    SQL> UPDATE TWEET
      2     SET
      3  WRITER_ID = 2
      4   WHERE ID = 101;
    
    1 row updated.
    

    Table data is changed:

    SQL> SELECT WRITER_ID, TWEET FROM TWEET;
    
     WRITER_ID TWEET
    ---------- -----
             1 T1
             2 T2
    
    SQL>
    

    Lets see what is the result of the above queries now:

    SQL> SELECT WRITER_ID, ROWNUM AS GENERATED_NUMBER FROM
      2  (SELECT DISTINCT WRITER_ID AS WRITER_ID FROM TWEET);
    
     WRITER_ID GENERATED_NUMBER
    ---------- ----------------
             1                1
             2                2
    
    SQL> SELECT DISTINCT ( WRITER_ID ),
      2                  RANK() OVER(ORDER BY WRITER_ID) AS GENERATED_NUMBER
      3    FROM TWEET;
    
     WRITER_ID GENERATED_NUMBER
    ---------- ----------------
             2                2
             1                1
    
    0 讨论(0)
  • 2021-01-27 07:01

    Try using this

    SELECT DISTINCT(CATEGORY) AS CategoryName, 
           ROW_NUMBER() OVER (ORDER BY CATEGORY) AS categoryId
    FROM APPLICATION 
    WHERE applications =? 
    
    0 讨论(0)
提交回复
热议问题