SQL 查询获取列中最常见的值

标签 sql postgresql

我有两个表如下 -

销售记录:

    Date    |   Customer   |    ItemSold 
-----------------------------------------
11/01/2013  |     Alex     |     Pen
12/01/2013  |     Rony     |     Paper
13/01/2013  |     Alex     |     Eraser
14/01/2013  |     Marty    |     Eraser
15/01/2013  |     Alex     |     Pen
16/01/2013  |     Rob      |     Paper
17/01/2013  |     Alex     |     Pencil
18/01/2013  |     Alex     |     Pen
19/01/2013  |     Ned      |     Pen
20/01/2013  |     Alex     |     Paper
21/01/2013  |     Alex     |     Pencil
22/01/2013  |     Ned      |     Pen
23/01/2013  |     Alex     |     Eraser
24/01/2013  |     Alex     |     Pen
25/01/2013  |     Alex     |     Pen
26/01/2013  |     Alex     |     Paper
27/01/2013  |     Ned      |     Paper
28/01/2013  |     Alex     |     Pen
29/01/2013  |     Alex     |     Eraser
30/01/2013  |     Alex     |     Pen
31/01/2013  |     Rony     |     Pencil
01/02/2013  |     Alex     |     Eraser
02/02/2013  |     Ned      |     Paper
03/02/2013  |     Alex     |     Pen

优先级:

ItemName    |    Priority
--------------------------
Pen         |       1
Paper       |       2
Pencil      |       3
Eraser      |       4

我想获得一个列表,以了解哪些客户可能会购买以下商品 -

Name   |   Item
----------------
Alex   |   Pen
Rob    |   Paper
Ned    |   Pen
Marty  |   Eraser
Rony   |   Paper

如果项目相同,则应选择优先级最高的项目。 Ned 分别购买了两次笔和纸,但应选择笔,因为它比纸具有更高的优先级。

这个的sql查询是什么?

最佳答案

从统计上看,您正在寻找的术语是模式。这是使用窗口/分析函数计算它的一种方法:

select customer, ItemSold
from (select customer, ItemSold, count(*),
             row_number() over (partition by customer order by count(*) desc, p.priority
                               ) as seqnum
      from sales s left outer join
           priority p
           on s.ItemSold = p.ItemName
      group by customer, ItemSold
     ) ci
where seqnum = 1;

关于SQL 查询获取列中最常见的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673428/

相关文章:

sql - SQL使用IN子句选择全部或全部不选择

sql - 使用 order by 时在大表上查询速度慢

postgresql - 按多维数据集从 Group 中删除重复的 NULL

postgresql - Golang gorm时间数据类型转换

python - 为什么 PostgreSQL 在合并实例时不增加 id_sequence 上的 last_value?

MySql MAX查询优化

SQL 服务器 2008 : complex Insert

mysql - 创建 mysql 插入/更新完整性触发器

sql - 从 postgres 数据库创建 JSON 文件

SQL - 将空单元格更新为 0( double )