使用rank函数优化sql查询

发布于 2024-08-21 23:04:47 字数 655 浏览 3 评论 0原文

此查询使用排名函数获取每组中的顶部项目。

我想将内部选择的数量减少到两个而不是三个。我尝试在最里面的查询中使用rank()函数,但无法让它与聚合函数一起工作。然后,如果不将“itemrank”包装在另一个 select 语句中,我就无法在“itemrank”上使用 where 子句。

有什么想法吗?

select *
from (
    select 
        tmp.*,
        rank() over (partition by tmp.slot order by slot, itemcount desc) as itemrank
    from (
        select
            i.name, 
            i.icon,
            ci.slot,
            count(i.itemid) as itemcount
        from items i
        inner join citems ci on ci.itemid = i.itemid
        group by i.name, i.icon, ci.slot    
    ) as tmp
) as popularitems
where itemrank = 1

编辑:使用sql server 2008

This query gets the top item in each group using the ranking function.

I want to reduce the number of inner selects down to two instead of three. I tried using the rank() function in the innermost query, but couldn't get it working along with an aggregate function. Then I couldn't use a where clause on 'itemrank' without wrapping it in yet another select statement.

Any ideas?

select *
from (
    select 
        tmp.*,
        rank() over (partition by tmp.slot order by slot, itemcount desc) as itemrank
    from (
        select
            i.name, 
            i.icon,
            ci.slot,
            count(i.itemid) as itemcount
        from items i
        inner join citems ci on ci.itemid = i.itemid
        group by i.name, i.icon, ci.slot    
    ) as tmp
) as popularitems
where itemrank = 1

EDIT: using sql server 2008

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏至、离别 2024-08-28 23:04:47

在 Oracle 和 Teradata(也许还有其他)中,您可以使用 QUALIFY itemrank = 1 来摆脱外部选择。这不是 ANSI 标准的一部分。

In Oracle and Teradata (and perhaps others too), you can use QUALIFY itemrank = 1 to get rid of the outer select. This is not part of the ANSI standard.

桃扇骨 2024-08-28 23:04:47

您可以在 Oracle 或 SQL Server 中使用公用表表达式。

语法如下:

WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )

仅当查询定义中提供了所有结果列的不同名称时,列名称列表才是可选的。

运行CTE的语句是:

SELECT <column_list>
FROM expression_name;

You can use Common Table Expressions in Oracle or in SQL Server.

Here is the syntax:

WITH expression_name [ ( column_name [,...n] ) ]
AS
( CTE_query_definition )

The list of column names is optional only if distinct names for all resulting columns are supplied in the query definition.

The statement to run the CTE is:

SELECT <column_list>
FROM expression_name;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文