根据联接表的另一列对一列进行重复计算

时间:2018-10-29 02:39:07

标签: sql postgresql

这很难在标题中解释,但是我有一列是联接表,我想根据一本书的type来计算角色出现的书的数量。

因此,如果cb.type = 2,那么我想count(cb.id) + 1是可行的。否则,对于所有其他类型,只需用count(cb.id)正常计数即可。

  SELECT
   CASE
     WHEN cb.type = 2 THEN count(cb.id) + 1
     ELSE count(cb.id)
   END AS book_count,
   c.*
  FROM characters c
         INNER JOIN character_books cb ON cb.character_id = c.id
  GROUP BY c.id, cb.type
  ORDER BY book_count DESC

上面的查询不起作用,因为我必须按c.id, cb.type进行分组,因此我没有得到该角色出现过的书籍总数。

现在,不考虑cb.type,查询将如下所示:

  SELECT count(cb.id) AS book_count, c.*
  FROM characters c
         INNER JOIN character_books cb ON cb.character_id = c.id
  GROUP BY c.id
  ORDER BY book_count DESC

但是,如果列cb.type = 2(实际上是一个按位列,为简单起见,此处仅使用数字2),那么我们应该向book_count添加一个额外的计数。

我将如何实现?

1 个答案:

答案 0 :(得分:1)

您需要条件聚合。我想你想要

SELECT c.id, 
       SUM(CASE cb.type = 2 THEN 2 ELSE 1 END) as book_count
FROM characters c INNER JOIN
     character_books cb
     ON cb.character_id = c.id
GROUP BY c.id
ORDER BY book_count DESC;