与count,max和group by相关

时间:2018-02-27 15:04:55

标签: sql group-by amazon-redshift

这是我的桌子。我试图根据他拥有的最大水果数量来获得与众不同的水果。

persons | fruits
   David apple
   David apple
   David apple
   David banana
   David orange
   Sam apple
   Sam banana
   Sam orange
   Sam orange
   Sam orange
   Sam orange
   Tom apple
   Tom banana
   Tom banana
   Tom orange

我希望将结果视为:

persons | fruits
   David apple
   Sam orange
   Tom banana

我尝试使用count和max函数并分组,但无法得到正确的结果。

2 个答案:

答案 0 :(得分:3)

您可以使用word = input("Enter a word: ") print("***") for letter in word: print(letter) print("***")

distinct on

你也可以在没有子查询的情况下编写它:

select distinct on (person) person, fruit
from (select person, fruit, count(*) as cnt
      from personfruits pf
      group by person, fruit
     ) pf
order by person, cnt desc;

然而,对于不熟悉select distinct on (person) person, fruit from personfruits pf group by person, fruit order by person, count(*) desc; 的人来说,这有点难以理解。

答案 1 :(得分:0)

根据我的理解,您希望看到每个人最常出现的水果。如果这是正确的,这应该可行

SELECT persons, fruits
FROM (
  SELECT 
    persons, 
    fruits,
    RANK() OVER(PARTITION BY persons ORDER BY FruitCount DESC) AS FruitRank -- Rank fruit count per person
  FROM (
    SELECT 
      persons, 
      fruits, 
      count(*) FruitCount -- get # rows per (person, fruit) combination
    FROM MyTable
    GROUP BY persons, fruits
  ) src
) src
WHERE FruitRank = 1 -- Return fruit with largest FruitCount, per person