【问题标题】:Get active and total bookings (from 1 table) for every user in users table获取用户表中每个用户的活跃和总预订量(来自 1 个表)
【发布时间】:2020-10-26 04:35:17
【问题描述】:

我有 2 张桌子:

  1. 用户:
  • 用户名(pk)
  1. 预订:
  • 用户名 (fk)
  • 状态(A = 活动,C = 已取消,D = 完成)

我愿意显示用户详细信息以及他们的活跃预订数和总预订数(其中总预订数将是特定用户“预订”表中的所有条目)。

要显示的表格: 用户名、有效预订(计数)、总预订(计数)

目前我无法对此进行有效查询。 我的数据库是 postgresql。

请帮忙。

谢谢

【问题讨论】:

    标签: sql database postgresql


    【解决方案1】:

    当您使用PostgreSQL 时,您可以利用Filter() 子句。您还必须使用Left Join,因为您需要user 表中每个用户的详细信息。所以写下你的查询如下:

    select 
    t1.username, 
    count(*) filter (where t2.status='A') as "Active_Bookings",
    count(t2.*) as "Total_Bookings"
    from users t1 left join bookings t2 on t1.username=t2.username
    group by 1
    

    根据评论编辑: Filter 子句由 PostgresqlSQLite 支持。对于其他人count with case 会做这件事。下面的查询应该适用于几乎所有其他数据库。

    select 
    t1.username, 
    count(case when t2.status='A' then 1 end)  as "Active_Bookings",
    count(t2.*) as "Total_Bookings"
    from users t1 left join bookings t2 on t1.username=t2.username
    group by t1.username
    

    你也可以使用sum(case when t2.status='A' then 1 else 0 end) as "Active_Bookings"

    【讨论】:

    • 似乎是一个好方法,但是“Total_Bookings”为每个用户返回 1,因为“bookings”表为空,我们如何使用 count(t2.*) 而不是 count(*) ?顺便说一句,我只是想知道数据库是 mysql 还是 sql server,那么有什么好的方法呢?非常感谢队友
    • 是的,更正 Count(*)count(t2.*) 还添加了对其他数据库的查询
    【解决方案2】:

    你可以试试下面的-

    select u.username,count(*) as total_booking,
           count(case when status='Active' then 1 end) as active_bookings
    from users u join bookings b on u.username=b.username
    group by u.username
    

    【讨论】:

      【解决方案3】:

      不太确定我是否理解了你的问题,但根据你提供的输入,试试这个,这应该可以工作

      select x.username,active_bookings,total_bookings from (
      (select username, count(status) as active_bookings from bookings where status='A' group by username)x  join (select username,count(status) as total_bookings  from bookings group by username)y on x.username=y.username);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多