根据最大列值对唯一行进行分组

时间:2018-06-29 13:07:28

标签: sql sql-server tsql

我有下表:

query   | update_date | website_id | device  | page    | impressions | clicks | position
--------+-------------+------------+---------+---------+-------------+--------+----------
kitchen | 2018-05-01  | 2          | desktop | http... | 11000       | 50     | 3
table   | 2018-05-01  | 2          | desktop | http... | 7000        | 40     | 3
kitchen | 2018-05-02  | 2          | desktop | http... | 11500       | 55     | 3
table   | 2018-05-02  | 2          | desktop | http... | 7100        | 35     | 3

我想输出一个关于每个唯一clicks的{​​{1}}表现最好的行。上表应提供以下输出:

query

到目前为止,我是这样的:

query   | update_date | website_id | device  | page    | impressions | clicks | position
--------+-------------+------------+---------+---------+-------------+--------+----------
table   | 2018-05-01  | 2          | desktop | http... | 7000        | 40     | 3
kitchen | 2018-05-02  | 2          | desktop | http... | 11500       | 55     | 3

这不符合预期,因为如果两行具有相同的点击量,我会得到多行。谁能帮我解决这个问题?

2 个答案:

答案 0 :(得分:1)

您可以将row_number()函数与 TIES 一起使用:

select top (1) with ties *
from search_console_query s
where . . .
order by row_number() over (partition by query order by click desc);

答案 1 :(得分:1)

尝试一下。

DECLARE @table AS TABLE (query NVARCHAR(MAX)
                        ,update_date DATE
                        ,website_id INT
                        ,device NVARCHAR(MAX)
                        ,page NVARCHAR(MAX)
                        ,impressions INT
                        ,clicks INT
                        ,POSITION INT
                        )
INSERT  INTO @table
VALUES  ('kitchen', '2018-05-01', 2, 'desktop', 'http...', 11000, 50, 3),
        ('table  ', '2018-05-01', 2, 'desktop', 'http...', 7000, 40, 3),
        ('kitchen', '2018-05-02', 2, 'desktop', 'http...', 11500, 55, 3),
        ('table  ', '2018-05-02', 2, 'desktop', 'http...', 7100, 35, 3);
WITH    cte
          AS (SELECT    *
              ,         ROW_NUMBER() OVER (PARTITION BY query ORDER BY clicks DESC) RN
              FROM      @table
             )
    SELECT  cte.query
     ,      cte.update_date
     ,      cte.website_id
     ,      cte.device
     ,      cte.page
     ,      cte.impressions
     ,      cte.clicks
     ,      cte.POSITION
    FROM    cte
    WHERE   RN = 1

应该足够近。

每个查询仅显示一行,您可以根据需要调整顺序以决定应优先考虑哪一行。

将更多字段添加到分区依据将允许您按其他选项分组。例如每月按查询分组等等。