查找每个年龄段中最常见的类型

时间:2019-06-01 12:51:59

标签: mysql

我正在考虑按十年划分年龄段,并找出哪种类型的频率更高。这比我预想的要难,但这是我尝试过的:

一个这样的表,名为:Set /P

choice.exe

第二个是有关sell_log的表格,其中包含ID和类型:

id id_film id_cust
1   2      2
2   3      4
3   1      5
4   4      3
5   5      1
6   2      4
7   2      3
8   3      1
9   5      3

第3个表,films是这个:

id_film      genres
    1        comedy
    2        fantasy
    3        sci-fi
    4        drama
    5        thriller

这是我做的代码:

customers

您认为正确的表格形式如何?

预期结果:例如 根据最常见的类型找到该类型并将其传递给该年龄组。

id_cust  date_of_birth_cust
1          1992-03-12
2          1999-06-25
3          1986-01-14
4          1985-09-18
5          1992-05-19

更新: 在答案中执行代码将给出以下信息:

select  id_cust,date_of_birth_cust,
    CASE
    WHEN date_of_birth_cust > 1980-01-01 and date_of_birth_cust < 1990-01-01 then ##show genre##
    WHEN date_of_birth_cust > 1990-01-01 and date_of_birth_cust < 2000-01-01 then ##show genre##
    ELSE ##show genre##
    END
from purchases 
INNER JOIN (
    select  id_cust 
    FROM sell_log
    group by id_cust
  ) customer.id_cust = sell_log.id_cust

我在做什么错

1 个答案:

答案 0 :(得分:0)

您可以使用CTE来获取每个年龄段和类型的搜索结果,然后使用它来获取每个年龄段的最大购买次数。最后再次加入CTE:

with cte as (
  select 
    CASE
      WHEN year(c.date_of_birth_cust) between 1980 and 1989 then 'from 1980 to 1989'
      WHEN year(c.date_of_birth_cust) between 1990 and 1999 then 'from 1990 to 1999'
      ELSE 'rest'
    END ages,
    f.genres,
    count(*) counter
  from sell_log s
  inner join films f on f.id_film = s.id_film 
  inner join customers c on c.id_cust = s.id_cust
  group by ages, f.genres
)

select c.ages, c.genres most_frequent_genre
from cte c inner join (
  select c.ages, max(counter) counter 
  from cte c
  group by c.ages
) g on g.ages = c.ages and g.counter = c.counter
order by c.ages

请参见demo
在样本数据中,所有关系都是结果。
结果:

| ages              | most_frequent_genre |
| ----------------- | ------------------- |
| from 1980 to 1989 | fantasy             |
| from 1990 to 1999 | comedy              |
| rest              | fantasy             |