【问题标题】:SQL select and count same tableSQL 选择并计算同一张表
【发布时间】:2016-10-07 09:08:52
【问题描述】:

我正在制作一个时事通讯工具,其中包含一个存储电子邮件地址的用户和打开的电子邮件 ID 的表格,用于计算每封已发送电子邮件的打开总数和唯一性。

我想显示一个详细的页面,其中包含有关电子邮件地址的用户的不同信息,并计算用户打开电子邮件的次数。

db表示例:

email_id | user_id | user
----------------------------
 1 | 1 | alpha@domain.com
 1 | 1 | alpha@domain.com
 1 | 1 | alpha@domain.com
 1 | 2 | beta@domain.com
 1 | 3 | gamma@test.org
 1 | 4 | mars@planet.net
 1 | 4 | mars@planet.net

网页结果:

║  User             ║ Times ║
╬═══════════════════╬═══════╣
║ alpha@domain.com  ║    3  ║
║ beta@domain.com   ║    1  ║
║ gamma@test.org    ║    1  ║
║ mars@planet.net   ║    2  ║

我尝试了以下查询,但它仅适用于第一行,然后截断其余部分:

SELECT DISTINCT user, count(DISTINCT user) as counttotal 
FROM newsletter_log 
where email_id = 1

【问题讨论】:

  • SELECT user, COUNT(*) AS counttotal FROM newsletter_log WHERE email_id = 1 GROUP BY user 怎么样?
  • 您使用的是哪个 DBMS?
  • 有效!谢谢 :) @FelixPamittan
  • @Otto,请在下面接受 jarlh 的回答。
  • 是的。我得等几分钟;)

标签: sql count distinct


【解决方案1】:

只需执行GROUP BY。使用COUNT(*) 计数。

select user, count(*) as counttotal
FROM newsletter_log
where email_id = 1
group by user

【讨论】:

    【解决方案2】:

    试试这个。

     select user,count(user) as times from newsletter_log where email_id = 1 group by user
    

    你不需要使用 distinct。只需使用分组依据。

    【讨论】:

      【解决方案3】:

      概念就像,您想根据用户组进行计数。因此,将用户视为组并按组进行计数。

      select user, count(1) as cnt
      FROM newsletter_log
      where email_id = 1
      group by user
      

      对于 Knowledge,您可以研究各种计数模式,例如 count(*)、count(1) 等。

      【讨论】:

        【解决方案4】:

        包括总数:

        SELECT email, IsNull(User, 'Total'), COUNT(User) [Count]
        FROM newsletter_log
        WHERE email = 1
        GROUP BY email, User
          WITH (ROLLUP)
        ORDER BY COUNT(User) DESC
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-02
          • 1970-01-01
          • 2018-11-26
          相关资源
          最近更新 更多