【问题标题】:How do you display one query result into 2 rows?如何将一个查询结果显示为 2 行?
【发布时间】:2020-12-04 10:56:18
【问题描述】:

所以这是对某事的基本查询。它在一行中显示每列的总数和百分比,但我希望它显示在 2 行中。第一行仅显示#s,而第二行仅显示第一行每列的百分比。

select column1,
       column2,
       column3,
       total,
       round((column1 / total) * 100, 2) as column1_percent,
       round((column2 / total) * 100, 2) as column2_percent,
       round((column3 / total) * 100, 2) as column3_percent,
       round((total / total) * 100, 2) as total_percent,
  from (select column1,
               column2,
               column3,
               (column1 + column2 + column3) as total
          from (select (select count(x) from table1 a, table2 b where ~~) as column1,
                       (select count(x) from table3 a, table4 b where ~~) as column2,
                       (select count(x) from table5 a, table6 b where ~~) as column3
                  from dual));

我该如何进行这项工作?帮助。

【问题讨论】:

  • 你为什么选择不使用正确的、明确的、标准的、可读的JOIN语法?
  • Gordon 所说的是逗号分隔的连接,例如from table1 a, table2 b ... 在 SQL 标准中引入显式连接(例如 from table1 a inner join table2 b on ...)之前使用。那是在1992。 (不过,Oracle 花了几年时间才采用它。)所以,要么你在这里处理一个非常古老的查询,要么你可能被一本非常糟糕的书、教程或老师教过 SQL。

标签: sql oracle


【解决方案1】:

您可以将Common Table ExpressionUNION ALL 一起使用

with cte as
(
select column1, column2, column3, (column1 + column2 + column3) as total
from (
  select
    (select count(x) from table1 a cross join table2 b where ~~) as column1,
    (select count(x) from table3 a cross join table4 b where ~~) as column2,
    (select count(x) from table5 a cross join table6 b where ~~) as column3
  from dual
)
)
select column1, column2, column3, total 
  from cte
 union all
select round((column1/total) *100, 2), 
       round((column2/total) *100, 2), 
       round((column3/total) *100, 2), 
       round((total/total) *100, 2) 
  from cte     

UNION ALL链接的查询中最上面的查询中发现别名

【讨论】:

  • 像魅力一样工作。谢谢。
猜你喜欢
  • 2017-08-11
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
  • 2015-11-11
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多