【问题标题】:SQL return distinct values and their combined count in one querySQL 在一个查询中返回不同的值及其组合计数
【发布时间】:2021-07-31 18:36:24
【问题描述】:

使用 MySQL 并且应该返回缺勤人数及其姓名。我查询所有学生并减去当天出现的学生的子查询。

这甚至可以在 1 个查询中完成吗?我知道如何使用 2 个单独的语句来实现,它们返回不同大小的语句,所以我不确定它们是否兼容。

姓名列表:

select distinct name 
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where name not in
(
  select distinct name 
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where sub_date = '2019-12-07'  
  )

计数:

select count(name) 
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where name not in
(
  select distinct name 
from submissions join hacker
on submissions.hacker_id=hacker.hacker_id
where sub_date = '2019-12-07'  
  )

【问题讨论】:

  • 嗨@user2415706,如果可能,请提供示例数据和预期输出。
  • 您好@user2415706 您可以根据假设使用 GROUP BY 子句将其组合起来,并且可以在获取示例数据后组合此查询。
  • 计数通常会在应用程序代码中解析

标签: mysql count distinct


【解决方案1】:

您可以使用 CTE 执行一次查询,然后使用 UNION 将计数和名称组合成一个结果。

WITH absentees as (select distinct name 
    from submissions join hacker
    on submissions.hacker_id=hacker.hacker_id
    where name not in
    (
      select distinct name 
    from submissions join hacker
    on submissions.hacker_id=hacker.hacker_id
    where sub_date = '2019-12-07'  
    )
)
SELECT * FROM absentees
UNION ALL
SELECT COUNT(*) FROM absentees

这会将总数作为结果中的最后一行。

【讨论】:

  • 好的,谢谢。这种写作风格是否等同于 CTE?将整个 CTE 放在括号内对我来说更容易阅读和记住。 With absentees AS (select distinct name from submissions join hacker on submissions.hacker_id=hacker.hacker_id where name not in ( select distinct name from submissions join hacker on submissions.hacker_id=hacker.hacker_id where sub_date = '2019-12-07' ))
  • 不,那是个错误。我实际上并不经常使用 CTE。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多