简体   繁体   中英

SQL two tables with different month values. Getting one result set for all the months

If I have two tables like this:

Table1

Month
1
3

Table 2

Month 
1
4

How do I get the following result set? Result Set

Month
1 
3
4

Use the UNION operator like this:

SELECT Month FROM Table1
UNION
SELECT Month FROM Table2

The SQL UNION operator combines two or more SELECT statements and produces a single result with unique values .

SELECT [Month]
FROM Table1
UNION
SELECT [Month]
FROM Table2

You will want to use a UNION to combine the results into a single set.

SELECT Month
FROM Table1
UNION
SELECT Month
FROM Table2

By default UNION only grabs distinct values, therefore your exact result. If you wanted duplicate values you could use UNION ALL which would show month 1 in your example twice.

Here is a good tutorial that shows the differences as well.

使用UNION

SELECT month FROM table1 UNION SELECT month FROM table2

从表1中选择月份从表2中选择月份

Here is my solution

declare @ temptable table( months varchar(10) )
inserto into @temptable(months)
select distinct Month from Table1

inserto into @temptable(months)
select distinct Month from Table2

select disticnt * from @temptable

Maybe there is a better way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM