【问题标题】:What's the best way to group SQL results by items batch?按项目批次对 SQL 结果进行分组的最佳方法是什么?
【发布时间】:2023-02-07 08:01:29
【问题描述】:

比如我有一个简单的表books

author book
Author-A Book-A1
Author-A Book-A2
Author-B Book-B1
Author-C Book-C1
Author-C Book-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)

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    通常的方法是JOIN 到一个映射表,如果需要,它可以是一个内联视图。

    SELECT
      author_group.group_label,
      COUNT(*)
    FROM
      books
    INNER JOIN
    (
      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
    )
      AS author_group
        ON author_group.author = book.author
    GROUP BY
      author_group.group_label
    

    【讨论】:

      猜你喜欢
      • 2012-03-29
      • 2010-09-11
      • 2017-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 2021-08-28
      相关资源
      最近更新 更多