sql—选择distinct字段和row num只是为了显示一个id号,这样会产生重复的数据

insrf1ej  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(277)

我有一个表应用程序,它有10列。类别是一列,此列具有重复的值。为了得到不同的值,我有一个查询 SELECT distinct(CATEGORY) as CategoryName FROM APPLICATION where applicationId=? .
我得到的结果没有任何问题。现在我想在这里添加一个列作为categoryid。没有这样的字段,我必须生成一个。我试着用下面的查询。

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

然后它显示重复的类别,rownum作为id。我可以用任何数字作为id,但是类别名称不应该重复。任何人都可以在一个查询中提出建议。

nimxete2

nimxete21#

请使用

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

aurhwmvo2#

您需要按如下方式使用子查询:

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.

表数据已更改:

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
rqenqsqc

rqenqsqc3#

试着用这个

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

相关问题