简体   繁体   English

SQL在DB2中对两个不同的列进行排序

[英]SQL order two different columns in DB2

I have following SQL: 我有以下SQL:

EXEC SQL
  DECLARE MY-CUR CURSOR WITH HOLD FOR
  SELECT ,ME.MSGTYPECD
         ,ME.MSGSUBTYPECD
  FROM    T_MESSAGE ME
ORDER BY  ME.MSGTYPECD ASC,
          ME.MSGSUBTYPECD ASC

The result set is lookin like this: 结果集如下所示:

MsgType     MsgSubType
300 
300 
515 
515 
515 
535 
535 
535 
598         515
598         515
598         515

What I would like to acomplish is following result: 我想完成的是以下结果:

MsgType     MsgSubType
300 
300 
515 
515 
515 
598         515
598         515
598         515
535 
535 
535 

There is also a possible solution to do this task with ORDER BY and CASE, but then I would need to "code" every MsgType which is a bit annoying. 还有一种可能的解决方案,可以使用ORDER BY和CASE来完成此任务,但是随后我需要为每个MsgType进行“编码”,这有点烦人。 (900 MsgTypes) and if a new one comes in I would need to change the query again. (900 MsgTypes),如果有新消息,则需要再次更改查询。

edit:// MsgType and MsgSubType is defined as character and the value (if not is filled) ist BLANK. edit:// MsgType和MsgSubType被定义为字符,并且值(如果未填充)为空白。

The definition looks like this: 定义如下所示:

with T_MESSAGE (MsgTypeCD, MsgSubTypeCD) as (values
  ('300', ' ')
, ('300', ' ')
, ('515', ' ')
, ('515', ' ')
, ('515', ' ')
, ('535', ' ')
, ('535', ' ')
, ('535', ' ')
, ('598', '515')
, ('598', '515')
, ('598', '515')
)

You haven't provided a formal description on exact rules of getting this result, but I'll try to guess. 您尚未提供获得此结果的确切规则的正式描述,但我会尝试猜测。

The query below returns the desired output. 下面的查询返回所需的输出。

with T_MESSAGE (MsgTypeCD, MsgSubTypeCD) as (values
  ('300', ' ')
, ('300', ' ')
, ('515', ' ')
, ('515', ' ')
, ('515', ' ')
, ('535', ' ')
, ('535', ' ')
, ('535', ' ')
, ('598', '515')
, ('598', '515')
, ('598', '515')
)
SELECT ME.MSGTYPECD, ME.MSGSUBTYPECD
FROM T_MESSAGE ME
ORDER BY 
  COALESCE(nullif(ME.MSGSUBTYPECD, ''), ME.MSGTYPECD)
, ME.MSGSUBTYPECD

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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