跨2个联合sql server表获取不同的值
我正在尝试使用联合获取两个表中的所有不同值。
这个想法是获取columnA列中所有唯一值的计数而不重复,以便我可以获得包含唯一columnA的所有列的总和。
这是我尝试过的(sql server express 2008)
select
count(Distinct ColumnA)
from
(
select Distinct ColumnA as ColumnA from tableX where x = y
union
select Distinct ColumnA as ColumnA from tableY where y=z
)
I'm trying to get all distinct values across 2 tables using a union.
The idea is to get a count of all unique values in the columnA column without repeats so that I can get a summation of all columns that contain a unique columnA.
This is what I tried (sql server express 2008)
select
count(Distinct ColumnA)
from
(
select Distinct ColumnA as ColumnA from tableX where x = y
union
select Distinct ColumnA as ColumnA from tableY where y=z
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
TableX 和 TableY 上的额外区别不是必需的;它们将在 tmp.ColumnA 子句中被删除。声明临时表应该可以消除可能阻止查询执行的歧义。
The extra distincts on TableX and TableY aren't necessary; they'll get stripped in the tmp.ColumnA clause. Declaring a temporary table should eliminate the ambiguity that might've prevented your query from executing.
使用“UNION”不会返回重复项。如果您使用“UNION ALL”,则将返回每个表中重复的 ColumnA 值。
Using a "UNION" will not return duplicates. If you used "UNION ALL" then duplicate ColumnA values from each table WOULD be return.
要在联合查询中获取不同的值,您可以尝试这样做
To get distinct values in Union query you can try this