跨2个联合sql server表获取不同的值

发布于 2024-08-15 03:51:11 字数 342 浏览 6 评论 0原文

我正在尝试使用联合获取两个表中的所有不同值。

这个想法是获取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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

半步萧音过轻尘 2024-08-22 03:51:11
SELECT COUNT(distinct tmp.ColumnA) FROM ( (SELECT ColumnA FROM TableX WHERE x=y) 
UNION (SELECT ColumnA FROM TableY WHERE y=z) ) as tmp

TableX 和 TableY 上的额外区别不是必需的;它们将在 tmp.ColumnA 子句中被删除。声明临时表应该可以消除可能阻止查询执行的歧义。

SELECT COUNT(distinct tmp.ColumnA) FROM ( (SELECT ColumnA FROM TableX WHERE x=y) 
UNION (SELECT ColumnA FROM TableY WHERE y=z) ) as tmp

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.

淑女气质 2024-08-22 03:51:11
SELECT COUNT(*)
FROM
(
SELECT DISTINCT ColumnA From TableX WHERE x = y
UNION
SELECT DISTINCT ColumnA From TableY WHERE y = z
) t

使用“UNION”不会返回重复项。如果您使用“UNION ALL”,则将返回每个表中重复的 ColumnA 值。

SELECT COUNT(*)
FROM
(
SELECT DISTINCT ColumnA From TableX WHERE x = y
UNION
SELECT DISTINCT ColumnA From TableY WHERE y = z
) t

Using a "UNION" will not return duplicates. If you used "UNION ALL" then duplicate ColumnA values from each table WOULD be return.

相思故 2024-08-22 03:51:11

要在联合查询中获取不同的值,您可以尝试这样做

Select distinct AUnion.Name,AUnion.Company from (SELECT Name,Company from table1 UNION SELECT Name,Company from table2)AUnion

To get distinct values in Union query you can try this

Select distinct AUnion.Name,AUnion.Company from (SELECT Name,Company from table1 UNION SELECT Name,Company from table2)AUnion
童话里做英雄 2024-08-22 03:51:11
SELECT DISTINCT Id, Name
FROM   TableA
UNION ALL
SELECT DISTINCT Id, Name
FROM   TableB
WHERE  TableB.Id NOT IN (SELECT Id FROM TableA)
SELECT DISTINCT Id, Name
FROM   TableA
UNION ALL
SELECT DISTINCT Id, Name
FROM   TableB
WHERE  TableB.Id NOT IN (SELECT Id FROM TableA)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文