[英]SQL: How to combine count results from multiple tables into multiple columns
我有两个结构相同的表,但我真正想要的只是一个不同的计数,即从单行到多列结果集。
我一直在获取语法错误,但到目前为止,仍然无法获得能够传递所需数据并通过解析器进行处理的东西。 我试图找出这是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
)
我也搞砸了4-5种不同的union
||用法 union all
无济于事。 很好奇SQL领域的人可能会有什么想法。 谢谢。
根据您所使用的数据库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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.