SQL:如何将多个表的计数结果组合成多个列

时间:2017-04-08 21:43:51

标签: sql

我的结构中有两个相同的表,但我真正想要的只是从每个表中的一行到多列结果集的明显计数。

我不断收到语法错误,但到目前为止还无法获得能够提供我想要的数据的东西,并通过解析器实现。我试图弄清楚这是否是一个SQL问题(可能是因为我使用的是网站的实现,而不是原生的MySQl / SQL / Oracle)或者是我的问题(更有可能)。

所以我想要的是两个不相关(和非主键)表,以将COUNT(DISTINCT列)返回到单个结果中。我尝试了几种不同的方法:

select 1,2 FROM
    (SELECT COUNT(DISTINCT col1) as 1 from table1),
    (SELECT COUNT(DISTINCT col2) as 2 from table2)
SELECT *
FROM (
    SELECT COUNT(DISTINCT col1) AS 1
    FROM table1 
    )
CROSS JOIN (
    SELECT COUNT(DISTINCT col2) AS 2
    FROM table2
    )

我也使用了union ||的4-5种不同用法union all无济于事。好奇的是,有人在SQL的艺术中学到了什么。感谢。

1 个答案:

答案 0 :(得分:1)

根据您的数据库RDBM,语法可能会发生一些变化。在ANSI Sql定义中,您的查询应为:

select col1, col2 FROM
    (SELECT COUNT(DISTINCT col1) as col1 from table1) as tab1,
    (SELECT COUNT(DISTINCT col2) as col22 from table2) as tab2

您必须为所有子查询添加alias。同时使用单词命名列,而不是数字,这样更容易理解。虽然我不记得是否允许将数字作为SQL ANSI中的别名。

没有子查询的别名,您可以像这样使用:

-- For MySql, PostgreSql, SQL Server (not sure though)
select (SELECT COUNT(DISTINCT col1)
          from table1) as col1,
       (SELECT COUNT(DISTINCT col2) as col22 
          from table2) as col2

-- For Oracle
select (SELECT COUNT(DISTINCT col1)
          from table1) as col1,
       (SELECT COUNT(DISTINCT col2) as col22 
          from table2) as col2
  from dual

-- For DB2
select (SELECT COUNT(DISTINCT col1)
          from table1) as col1,
       (SELECT COUNT(DISTINCT col2) as col22 
          from table2) as col2
  from sysibm.sysdummy1

旁注:如果用双引号"(这是SQL ANSI并且可以在任何地方使用)包围它,可以使用数字作为别名:

select "1", "2" FROM
    (SELECT COUNT(DISTINCT col1) as "1" from table1) a, --don't forget the table alias
    (SELECT COUNT(DISTINCT col2) as "2" from table2) b

Mysql还允许你使用后退标记:

select `1`, `2` FROM
    (SELECT COUNT(DISTINCT col1) as `1` from table1) a,
    (SELECT COUNT(DISTINCT col2) as `2` from table2) b