将两列连接到不同表中的一列中

时间:2013-01-18 06:00:36

标签: sql sql-server sql-server-2008 tsql

我正在使用SQL Server 2008.我有两个SQL查询

select Course 
from StudentDB.dbo.Student 
where RollNo = 130

select Course 
from StudentDB.dbo.Courses 
where Course is not null

第一个查询将返回以下值

MSc

,第二个查询将返回

MCA
MSc
CSE
ECE
EEE

我需要加入这些查询,并希望得到像这样的输出

MSc
MCA
CSE
ECE
EEE

即将第二个查询的结果附加到第一个查询并删除重复值。

请注意我需要在结果的顶部首先查询结果。这里Msc是第一个值,因为它是第一个查询的结果。我试过工会。但它返回第二个查询本身的结果。因此,这些查询的结合将无济于事。

3 个答案:

答案 0 :(得分:4)

我不是DISTINCT的粉丝;根据JW的答案,这将为您提供与StudentDB.dbo.Student中的值一起排序的不同值列表:

SELECT Course
FROM
(
    select Course, 1 ord from StudentDB.dbo.Student where RollNo = 130
    UNION
    select Course, 2 ord from StudentDB.dbo.Courses where Course is not null
) s
GROUP BY Course
ORDER BY min(ord)

答案 1 :(得分:0)

可能是因为服务器中的默认排序规则是SQL_Latin1_General_CP1_CI_AS,这意味着它是不区分大小写(CI)。

这使您的Msc与MSC相同。 您需要将排序规则更改为不区分大小写的其他排序规则。

查看可能的排序规则: http://msdn.microsoft.com/en-us/library/ms144250(v=sql.105).aspx

请参阅COLLATE的用法 http://blog.sqlauthority.com/2007/04/30/case-sensitive-sql-query-search/

答案 2 :(得分:0)

只需在SQL Server中运行此脚本即可获得结果,您也可以在存储过程中使用它。

SELECT Course,1 ord INTO #tmpTable FROM Student

INSERT #tmpTable
SELECT Course,2 ord FROM Courses WHERE Course IS NOT NULL 
AND Course NOT IN(SELECT Course FROM Student)

SELECT Course FROM #tmpTable ORDER BY ord

DROP TABLE #tmpTable