postgresql 按项目批处理对SQL结果进行分组的最佳方法是什么?

k4emjkb1  于 2023-02-08  发布在  PostgreSQL
关注(0)|答案(2)|浏览(123)

例如,我有一个简单的表books
| 作者|书|
| - ------|- ------|
| 作者-A|手册-A1|
| 作者-A|手册-A2|
| 作者B|手册-B1|
| 作者C|书本-C1|
| 作者C|书本-C2|
我需要计算每个作者的书,所以我会写:

select author, count(*) from books
group by author

# Author-A = 2
# Author-B = 1
# Author-C = 2

但现在我需要按作者群体来数书:

groupA = ['Author-A', 'Author-C'],
groupB = ['Author-B']

select authorGroup, count(*) from books
group by {
  case author in groupA -> 'groupA'
  case author in groupB -> 'groupB'
} as authorGroup

# ['Author-A', 'Author-C'] = 4
# ['Author-B'] = 1

这些组可以是不同的,并且来自另一个模块。编写此请求的最佳方式是什么?可能没有联合,例如:

select author as 'groupA', count(*) from books
where author in { groupA }
  union
select author as 'groupB', count(*) from books
where author in { groupB }

因为可能会有很多团体提出请求(约20-30)
问题是,这些群体可能是绝对动态的:我可以在一个请求中作为一个组请求['Author-A', 'Author-B'],在另一个组中请求['Author-B', 'Author-C']
例如,一个群体不像作者的国家或流派,它可以是完全动态的。

l7wslrjt

l7wslrjt1#

通常的方法是将JOINMap到Map表,如果需要的话,Map表可以是内嵌视图 (尽管我推荐使用实际的表,它可以被索引)

WITH
  author_group AS
(
  SELECT 'Author-A' AS author, 'Group-A' AS group_label
  UNION ALL
  SELECT 'Author-B' AS author, 'Group-B' AS group_label
  UNION ALL
  SELECT 'Author-C' AS author, 'Group-A' AS group_label
)
SELECT
  author_group.group_label,
  COUNT(*)
FROM
  books
INNER JOIN
  author_group
    ON author_group.author = books.author
GROUP BY
  author_group.group_label

使用CASE表达式也可以获得类似的结果,但它的伸缩性不是很好...

WITH
  mapped_author AS
(
  SELECT
    *,
    CASE author
      WHEN 'Author-A' THEN 'Group-A'
      WHEN 'Author-B' THEN 'Group-B'
      WHEN 'Author-C' THEN 'Group-A'
    END
      AS author_group
  FROM
    books
)
SELECT
  author_group,
  COUNT(*)
FROM
  mapped_author
GROUP BY
  author_group
jc3wubiy

jc3wubiy2#

首先,您需要创建一个新表,显示作者所在的组。
以后你就数数
就像这样:

select distinct a.group_auth, count(a.book) over (partition by a.group_auth) 
from
(select 
       case when b.Author in [groupA] then 'groupA', 
             when b.Author  in [groupB] then 'groupB' 
        end case as group_auth,
        b.book as book
from books b
) as a
;

相关问题