从多个表中选择 COUNT(DISTINCT [name])
我可以执行以下 SQL Server 从一个表中的列中选择不同(或不重复的名称)的操作,如下所示:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable]
但是,如果我有多个表(所有这些表都包含名为 [Name] 的名称字段)并且我该怎么办?需要知道两个或多个表中非重复名称的计数。
如果我运行这样的命令:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable1], [MyTable2], [MyTable3]
我收到错误“列名‘名称’不明确”。
附言。所有三个表 [MyTable1]、[MyTable2]、[MyTable3] 都是先前选择的产物。
I can perform the following SQL Server selection of distinct (or non-repeating names) from a column in one table like so:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable]
But what if I have more than one table (all these tables contain the name field called [Name]) and I need to know the count of non-repeating names in two or more tables.
If I run something like this:
SELECT COUNT(DISTINCT [Name]) FROM [MyTable1], [MyTable2], [MyTable3]
I get an error, "Ambiguous column name 'Name'".
PS. All three tables [MyTable1], [MyTable2], [MyTable3] are a product of a previous selection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
澄清后,使用:
如果我理解正确,使用:
UNION
将删除重复项;UNION ALL
不会,而且速度更快。After the clarification, use:
If I understand correctly, use:
UNION
will remove duplicates;UNION ALL
will not, and is faster for it.编辑:看到最近的评论后必须更改。
这能给你你想要的吗?合并所有表中的行后,这将给出每个人的计数。
EDIT: Had to change after seeing recent comment.
Does this give you what you want? This gives a count for each person after combining the rows from all tables.
这是另一种方法:
Here's another way:
如果您每个表的列数不同,例如:
并且您想要计算不同列名称的不同值的数量,那么什么在 AthenaSQL 中,使用
CROSS JOIN
对我很有用,因为您的输出只有一行,它只是 1 个组合:将返回一个包含一行的表,并且他们的计数:
In case you have different amounts of columns per table, like:
And you want to count the amount of distinct values of different column names, what it was useful to me in AthenaSQL was to use
CROSS JOIN
since your output would be only one row, it would be just 1 combination:Would return a table with one row and their counts:
一个更新的解决方案,来自 PostgreSQL 示例,获得所有唯一股票(在本例中)名称的授权总数,包含在一个漂亮的视图中:
...
A more recent solution, from PostgreSQL example, to get a grant total of all unique stock (in this case) names, wrapped up in a nice VIEW:
...