为什么默认情况下分组查询对A到Z进行排序?

Muh*_*man 1 sql sql-server sorting union visual-studio

我创建了一个查询,以从表的列中获取通过该查询不为空的值:

Select * from(
SELECT       OEID, Chest_Pain as Head, Chest_PainComment as Detail
FROM            tblComplaints
union

SELECT       OEID, SOB as Head, SOBComment as Detail
FROM            tblComplaints
union

SELECT        OEID, PND as Head, Cyanosis as Detail FROM tblComplaints
union

SELECT        OEID, Odema_Feet as Head, Vertigo + as Detail  From tblComplaints
union

SELECT       OEID, DM as Head, DMComment as Detail
FROM            tblComplaints
union

SELECT       OEID, RS as Head, RSComment as Detail
FROM            tblComplaints

) as t
where (Head is not null and ltrim(rtrim(Head)) <> '')
and OEID = 6012
Run Code Online (Sandbox Code Playgroud)

数据很好,但问题是此查询自动对输出结果进行A到Z排序。我需要做的是通过输入每一行的方式来获得结果。

例如:目前,我得到的查询结果如下:

Head                            Detail
Chest_Pain                      Chest_PainComment
DM                              DmComment
Odema_Feet                      Vertigo
PND                             Cyanosis
RS                              RSComment
Run Code Online (Sandbox Code Playgroud)

我希望它像这样:

Head                            Detail
Chest_Pain                      Chest_PainComment
RS                              RSComment
PND                             Cyanosis
DM                              DMComment
Run Code Online (Sandbox Code Playgroud)

最重要的是,在我的查询中不应出现从A到Z的排序。我不知道为什么在查询中发生这种A到Z排序,而我没有在任何地方对其进行排序。

我将感谢您的帮助。

Gor*_*off 6

SQL表和结果集表示无序集(从技术上讲,是多集)。除非您指定order by子句,否则没有排序。因此,在其中添加一个:

select OEID, Head, Detail
from ((select OEID, Chest_Pain as Head, Chest_PainComment as Detail, 1 as ord
       from tblComplaints
      ) union all
      (select OEID, SOB as Head, SOBComment as Detail, 2
       from tblComplaints
      ) union all
      (select OEID, PND as Head, Cyanosis as Detail, 3
       from tblComplaints
      ) union all
      (select OEID, Odema_Feet as Head, Vertigo as Detail, 4
       from tblComplaints
      ) union all
      (select OEID, DM as Head, DMComment as Detail, 5
       from tblComplaints
      ) union all
      (select OEID, RS as Head, RSComment as Detail, 6
       from tblComplaints
      )
     ) as t
where Head is not null and 
      ltrim(rtrim(Head)) <> '' and
      OEID = 6012
order by ord;
Run Code Online (Sandbox Code Playgroud)

条件head is not null是多余的。该<>注意到了这一问题。

您可以将查询简化为:

select v.*
from tblComplaints t cross apply
     (values (Chest_Pain, Chest_PainComment, 1),
             (SOB, SOBComment, 2),
             . . .  -- continue with the other values
     ) v(Head, Detail, ord)
where ltrim(rtrim(Head)) <> '' and
      OEID = 6012
order by ord;
Run Code Online (Sandbox Code Playgroud)

如果您的数据不小,那么您应该会发现它也具有更好的性能。

最后,要回答您的问题,请union删除重复项。在这种情况下,似乎是通过对数据进行排序来实现的。 您不能依赖这种排序方式-例如,还有其他方法可以删除重复项。

类似地,using union all不会对数据进行排序,但这并不意味着结果集将按照您想要的顺序排列,除非您有明确的order by