使用UNION - SQL的自定义结果顺序

时间:2011-02-11 14:09:21

标签: sql sql-server database tsql

我有一个相当简单的任务,我需要选择具有特定字段的行,其值为1,然后是值2,最后是所有其他值为0的行。

我使用联接来获取哪些项目是哪个类别的成员。我认为执行3选择并使用联合将结合正确的顺序,但我错了:)

我的SQL如下:

SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 1 
UNION 
SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 2
UNION 
SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 0

我的结果不是以1,然后是2然后0来命令..我在这里做错了什么?

*解决方案* 谢谢你的帮助。下面是我正在使用的最终SQL。

SELECT * FROM tblcompanycategory 
    INNER JOIN tblcompany
    ON tblcompany.idcompany = tblcompanycategory.idcompany
    WHERE tblcompanycategory.idcategory = @category 
    ORDER BY CASE tblcompany.intpremium WHEN 1 THEN 0 WHEN 2 THEN 1 WHEN 0 THEN 2 END

3 个答案:

答案 0 :(得分:2)

与所有好的集合运算符一样,UNION语句在订购数据时是不可知的。

然而,您可以执行的操作是使用精心设计的ORDER BY语句运行一个select语句,例如:

... ORDER BY CASE tblCompany.IntPremium WHEN 1 THEN 0 WHEN 2 THEN 1 WHEN 0 THEN 2 END

答案 1 :(得分:1)

按照union子句中select语句的顺序不会发生排序。最简单的方法是通过以下方式添加订单:

SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 1 
UNION 
SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 2
UNION 
SELECT * FROM tblcompanycategory 
INNER JOIN tblcompany
ON tblcompany.idcompany = tblcompanycategory.idcompany
WHERE tblcompanycategory.idcategory = @category AND tblcompany.intpremium = 0

ORDER BY CASE intpremium WHEN 1 THEN 1 WHEN 2 THEN 2 WHEN 0 THEN 3 END

答案 2 :(得分:0)

您需要在三个select语句中添加一个列,其中包含一个“分类”结果的文字值。然后按该列排序。