【问题标题】:SQLite3 - Counting number of duplicate and non-duplicate books each user ownsSQLite3 - 计算每个用户拥有的重复和非重复书籍的数量
【发布时间】:2021-06-27 17:35:01
【问题描述】:

我正在创建一个数据库,用于跟踪书籍、用户以及每个用户拥有的书籍。用户可以拥有一本书的多个副本,由他们的书 ID 指定。我要特别计算的是为每个用户名显示他们拥有的所有书籍的数量以及他们拥有的非重复书籍的数量。我在下面进行了尝试,但数字似乎不正确。例如,在我的 select 语句之后,它说 Sammy 的重复书籍总数为 4,他的非重复书籍总数为 3。

当您实际查看 owns 表中的数据时,您可以看到真正的值是 Sammy 的总重复书籍是 3+2+1+1 = 7 本书,而他的非重复书籍总数将只是是他收藏中唯一 book_id 的总数,只有 4 个。

我不确定我的查询逻辑有什么问题,希望能得到一些帮助。

架构:

CREATE TABLE IF NOT EXISTS books(
      id integer NOT NULL primary key UNIQUE, 
      title text NOT NULL UNIQUE,
      genre text NOT NULL, 
      price integer NOT NULL,
      units_available integer NOT NULL 
      );  
      
CREATE TABLE IF NOT EXISTS users(
      username text primary key NOT NULL UNIQUE, 
      password text NOT NULL 
      );

CREATE TABLE IF NOT EXISTS owns(
      owners_username integer NOT NULL,
      book_id integer NOT NULL,
      quantity integer NOT NULL,
      PRIMARY KEY (owners_username, book_id),
      FOREIGN KEY (owners_username) REFERENCES users (username),
      FOREIGN KEY (book_id) REFERENCES books (id)
      );
      

拥有表中的所有内容/每个用户拥有的所有书籍及其数量:

select * from owns;

owners_username  book_id  quantity
---------------  ---------  --------
Bobby            47911      1
Bobby            49286      1
Bobby            55622      1
Sammy            50818      3
Sammy            49290      2
Sammy            55617      1
Sammy            6555       1
Andrew           50546      1
Andrew           49290      4
Andrew           48401      1

当我尝试计算每个用户拥有的重复和非重复书籍的数量时:

select owners_username, dup_count, nodup_count
from
   (select owners_username, count(quantity) as dup_count
   from (select owners_username, quantity from owns)
   group by owners_username)

   natural join

   (select owners_username, count(quantity) as nodup_count
   from (select distinct owners_username, quantity from owns)
   group by owners_username);


owners_username  dup_count  nodup_count
---------------  ---------  -----------
Andrew            3          2
Bobby             3          1
Sammy             4          3

【问题讨论】:

  • 你能解释一下duplicated books是什么意思吗? Sammy 只有 1 本书 55617 和 6555。那么为什么他的副本是 7?
  • 他有4个不同的书ID,他拥有3份bookid 50818,2份bookid 49290,1份55617,1份6555。我想统计他拥有的书总数对于所有 bookid 的组合,所以如果我将所有副本加在一起 ​​3 + 2 + 1 + 1 = 7 个重复的副本,但只有 4 个唯一/非重复的书。

标签: sql database sqlite select count


【解决方案1】:

您需要为每个用户提供quantity 列的总和以及不同book_ids 的数量:

SELECT owners_username,
       SUM(quantity) dup_count,
       COUNT(DISTINCT book_id) nodup_count 
FROM owns
GROUP BY owners_username

请参阅demo
结果:

owners_username dup_count nodup_count
Andrew 6 3
Bobby 3 3
Sammy 7 4

【讨论】:

    猜你喜欢
    • 2012-01-14
    • 2015-03-29
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多