【问题标题】:How do I get this SQL query?如何获取此 SQL 查询?
【发布时间】:2020-08-21 14:00:17
【问题描述】:

模型是:

Group {
    Id : int
}

Item {
    GroupId : int
    Status : int
}

如何查询这个输出表:

GroupID | TotalItemCount | ItemsWithStatus = 1 | ItemsWithStatus = 2

【问题讨论】:

  • “模型”。数据库有表和列。此外,MySQL 和 SQL Server 是非常不同的数据库。

标签: sql join database-design


【解决方案1】:

我怀疑你想要:

select g.groupid, count(*) as numitems,
       sum(case when i.status = 1 then 1 else 0 end) as status_1,
       sum(case when i.status = 2 then 1 else 0 end) as status_2
from items i join
     groups g
     on i.groupid = g.id
group by g.groupid;

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2018-10-31
    • 2019-09-22
    • 2014-10-26
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多