【问题标题】:How to construct a table from multiple and independent select statement?如何从多个独立的select语句构造一个表?
【发布时间】:2019-02-01 09:43:07
【问题描述】:

我查看了一些相关问题,但找不到帮助。

我正在尝试创建一个显示已完成注册步骤的公司数量的静态表。我已经完成了所有繁重的工作,我可以使用一个简单的 select 语句来查看有多少完成了,比如说,第 1 步。但我想写一个 select 语句,其中包含 step 1 step 2 step 3 (columns) with number (values) 的公司完成每个步骤.

step table 

----------------------------------------------------
progress_id | label | level | score | is_completed | 
----------------------------------------------------

progress_id:我们正在跟踪进度的公司

标签:步骤级别标签,例如:公司邮箱已验证,

级别:说第一步,

得分:例如:20%,

is_completed:真/假

你看这个,我可以简单地做到:

select count(*) step_one_count from step where level = 1 and is_completed = true;

----------------
step_one_count |
----------------
20

select count(*) step_two_count from step where level = 2 and is_completed = true;

----------------
step_two_count |
----------------
10

然后我需要编写一个选择语句,无论是使用子查询还是在下面实现这个结果

----------------------------------------------------
step_one_count | step_two_count | step_three_count |
----------------------------------------------------
20               10               40

【问题讨论】:

  • 标记您实际使用的唯一 DBMS。
  • 看来你的 step_three_count 将是 30
  • 我会选择基本的 GROUP BY:select level, count(*) from step where is_completed = true group by level
  • @YogeshSharma:很抱歉我确实添加了它,但我不知道为什么没有添加它
  • @ZaynulAbadinTuhin:数字并不重要

标签: sql postgresql


【解决方案1】:

我怀疑你想要条件聚合,在MySQL你可以这样做:

SELECT SUM( (level = 1 and is_completed = true) ) AS step_one_count,
       SUM( (level = 2 and is_completed = true) ) AS step_two_count,
       SUM( (level = 3 and is_completed = true) ) AS step_three_count
FROM step s;

以标准方式,您可以使用 CASE 表达式代替:

SELECT SUM(CASE WHEN level = 1 and is_completed = true THEN 1 ELSE 0 ) AS step_one_count,
       . . . 
FROM step s;

编辑:当您标记DBMS 时,您可以使用FILTER

SELECT COUNT(*) FILTER (WHERE level = 1 and is_completed = true) AS step_one_count,
       COUNT(*) FILTER (WHERE level = 2 and is_completed = true) AS step_two_count,
       COUNT(*) FILTER (WHERE level = 3 and is_completed = true) AS step_three_count,
FROM step s;

【讨论】:

  • 我无法说出我对你们所有人的 stackoverflow 有多爱。只适用于 EDIT 代码。非常感谢
【解决方案2】:

用例当

   select 
   sum(case when level = 1 and is_completed = true then 1 else 0 end) 
   as  step_one_count,
   sum(case when level = 2 and is_completed = true then 1 else 0 end) 
   as step_two_count,
  sum(case when level in (1,2) and is_completed = true then 1 else 0 end)
   as step_three_count        
    from step  

【讨论】:

  • ERROR: function sum(boolean) does not exist LINE 1: select sum(level = 1 and is_completed = true) as step_one_co...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
  • 2021-12-25
  • 2014-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多