选择不同的字段和行号只是为了显示一个 id 号会产生重复的数据

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

我有一个 table 应用程序,它有 10 列。类别是一列,​​此列具有重复值。为了获得不同的值,我有一个查询

SELECT distinct(CATEGORY) as CategoryName FROM APPLICATION where applicationId=?.

我得到的结果没有任何问题。现在我想在这里添加另一列作为 categoryId。没有这样的字段,我必须生成一个。我尝试了以下查询。

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

然后显示重复的类别,id 为rownum。我可以使用任何数字作为 id,但类别名称不应重复。任何人都可以建议如何在单个查询中执行此操作。

您需要使用子查询如下:

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

您还可以使用 analytical function 如下:

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

示例:

我有以下数据:

SQL> SELECT WRITER_ID, TWEET FROM TWEET;

 WRITER_ID TWEET
---------- -----
         1 T1
         1 T2

SQL>

查看以上两个查询的输出:

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

现在,让我更改我的数据

SQL> UPDATE TWEET
  2     SET
  3  WRITER_ID = 2
  4   WHERE ID = 101;

1 row updated.

Table数据更改:

SQL> SELECT WRITER_ID, TWEET FROM TWEET;

 WRITER_ID TWEET
---------- -----
         1 T1
         2 T2

SQL>

让我们看看上面查询的结果是什么:

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

试试这个

SELECT DISTINCT(CATEGORY) AS CategoryName, 
       ROW_NUMBER() OVER (ORDER BY CATEGORY) AS categoryId
FROM APPLICATION 
WHERE applications =? 

请使用

SELECT CATEGORY as CategoryName, sum(rownum) FROM APPLICATION WHERE applicationId=? GROUP BY CATEGORY