为什么oracle的order by不能正常工作?

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

所以基本上我在运行这个sqloracle程序,我想打印5行,并根据平均评级对它们进行排序。到目前为止,我有两个问题:它不断打印重复值,它不是按评级排序。
表格如下:

Title_basics
----------------------
Primarytitle NVARCHAR2(950)
Genres NVARCHAR2(350)
Endyear VARCHAR2(4)

Title_ratings
--------------------------------------
Averagerating Number(5,2)
COLUMN Title FORMAT a30 HEADING Title
COLUMN Genres FORMAT a20 HEADING Genres
COLUMN Rating FORMAT 99.99 HEADING Rating
COLUMN Year FORMAT a7 HEADING Format

SELECT *
FROM ( SELECT DISTINCT tb.primarytitle AS Title, tb.genres AS Genres, tr.averagerating AS Rating, tb.endyear AS Year
                FROM title_basics tb, title_ratings tr
                WHERE tb.genres LIKE '%Comedy%' AND (tb.endyear = '2001' OR tb.endyear = '2002' OR tb.endyear = '2003' OR tb.endyear = '2004' OR tb.endyear = '2005')
                ORDER BY tb.endyear DESC
)
WHERE ROWNUM <= 5;
z3yyvxxp

z3yyvxxp1#

将order by子句置于子查询之外-

SELECT *
FROM ( SELECT DISTINCT tb.primarytitle AS Title, tb.genres AS Genres, tr.averagerating AS Rating, tb.endyear AS Year
                FROM title_basics tb, title_ratings tr
                WHERE tb.genres LIKE '%Comedy%' AND (tb.endyear = '2001' OR tb.endyear = '2002' OR tb.endyear = '2003' OR tb.endyear = '2004' OR tb.endyear = '2005')

)
WHERE ROWNUM <= 5
ORDER BY Year DESC
3gtaxfhh

3gtaxfhh2#

你可以用 FETCH 子句指定要返回的行数。它比rownum(docs)灵活得多

SELECT DISTINCT tb.primarytitle     AS title,
                tb.genres           AS genres,
                tr.averagerating    AS rating,
                tb.endyear          AS year
  FROM title_basics   tb,
       title_ratings  tr
 WHERE tb.genres LIKE '%Comedy%' AND
       ( tb.endyear = '2001' OR
         tb.endyear = '2002' OR
         tb.endyear = '2003' OR
         tb.endyear = '2004' OR
         tb.endyear = '2005' )
 ORDER BY tb.averagerating DESC
FETCH FIRST 5 ROWS ONLY;
q8l4jmvw

q8l4jmvw3#

你的问题真没道理。平均分级表中没有联接列。可能有一列将其与另一个表联系起来:

SELECT *
FROM (SELECT tb.primarytitle AS Title, tb.genres AS Genres, tr.averagerating AS Rating, tb.endyear AS Year
      FROM title_basics tb JOIN
           title_ratings tr
           ON tb.? = tr.?   -- presumably some JOIN condition here
      WHERE tb.genres LIKE '%Comedy%' AND 
            tb.endyear IN ('2001', '2002', '2003', '2004', '2005')
      ORDER BY tr.averagerating DESC
     ) br
WHERE ROWNUM <= 5;

这个 ? 用于指定 JOIN 条件。
如果正确地联接表,则可能不需要 SELECT DISTINCT .

相关问题