从SQL Server中的多个表中获取不同的列值

时间:2023-01-25 09:37:59

I have following data in SQL Server tables:

我在SQL Server表中有以下数据:

id  Sal
1   100
2   200

id  Wages
1   600
2   800

I want the output as following:

我希望输出如下:

id   Sal/Wages
1    100
1    600
2    200
2    800

How I can do that using a SELECT statement in SQL Server?

我如何在SQL Server中使用SELECT语句?

2 个解决方案

#1


2  

Use UNION ALL

使用UNION ALL

Select Id, sal as [sal/wages]
from table1
UNION ALL
Select Id, wages as [sal/wages]
from table2
Order by id,[sal/wages]

If you don't need duplicate records then just use UNION

如果您不需要重复记录,那么只需使用UNION

#2


1  

use union all:

使用union all:

select id, sal as [sal/Wages] from table1
union all
select id, wages as [sal/Wages] from table2
order by 1

Note that I've used union all and not union, because union removes duplicates from resulting set. Sometimes it might be useful, but not in your case, I think.

请注意,我使用了union all而不是union,因为union从结果集中删除了重复项。我认为有时可能会有用,但不是在你的情况下。

#1


2  

Use UNION ALL

使用UNION ALL

Select Id, sal as [sal/wages]
from table1
UNION ALL
Select Id, wages as [sal/wages]
from table2
Order by id,[sal/wages]

If you don't need duplicate records then just use UNION

如果您不需要重复记录,那么只需使用UNION

#2


1  

use union all:

使用union all:

select id, sal as [sal/Wages] from table1
union all
select id, wages as [sal/Wages] from table2
order by 1

Note that I've used union all and not union, because union removes duplicates from resulting set. Sometimes it might be useful, but not in your case, I think.

请注意,我使用了union all而不是union,因为union从结果集中删除了重复项。我认为有时可能会有用,但不是在你的情况下。