如何输出组中的所有列而不将它们放在group by子句中?

时间:2016-10-05 10:05:41

标签: sql oracle

假设我有一个这样的表:

Name    Priority    Country    SomeData
Paul           1    USA             456
Paul           2    England        7898
Paul           3    Austria          56
Fred           2    Belgium         156
Fred           4    France         8979
Carl           3    Canada          569
Jane           1    Peru             69

我想做这样的事情:

select Name, min(Priority), Country, SomeData
from dual
group by Name

但我不想按所有栏目分组。

结果应如下所示:

Name    Priority    Country    SomeData
Paul           1    USA             456
Fred           2    Belgium         156
Carl           3    Canada          569
Jane           1    Peru             69

我知道这很简单但我找不到任何东西。
我该怎么做?

1 个答案:

答案 0 :(得分:3)

您可以使用内联视图(或CTE)添加按所需顺序对数据进行排名的额外列,然后使用仅获得最高排名的外部查询:

var username = "ck_????????????????????????????????????????";
var password = "cs_????????????????????????????????????????";
var up = username + ":" + password;
var authHeader = "Basic " + btoa(username + ":" + password);

WooClient.prototype.getProducts = function () {
    return $.ajax({
        url: "/myshop/wp-json/wc/v1/products",
        type: "get",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", authHeader);
            return true;
        }
    }).then(function (data) {
        return data;
    });
};

在CTE中快速演示您的数据:

select name, priority, country, somedata
from (
  select t.*, dense_rank() over (partition by name order by priority) as rn
  from your_table t
)
where rn = 1;

或者如果您想坚持分组,可以使用keep dense_rank first syntax

with t(Name, Priority, Country, SomeData) as (
  select 'Paul', 1, 'USA', 456 from dual
  union all select 'Paul', 2, 'England', 7898 from dual
  union all select 'Paul', 3, 'Austria', 56 from dual
  union all select 'Fred', 2, 'Belgium', 156 from dual
  union all select 'Fred', 4, 'France', 8979 from dual
  union all select 'Carl', 3, 'Canada', 569 from dual
  union all select 'Jane', 1, 'Peru', 69 from dual
)
select name, priority, country, somedata
from (
  select t.*, row_number() over (partition by name order by priority) as rn
  from t
)
where rn = 1;

NAME   PRIORITY COUNTRY   SOMEDATA
---- ---------- ------- ----------
Carl          3 Canada         569
Fred          2 Belgium        156
Jane          1 Peru            69
Paul          1 USA            456