[英]DB2 Grouping and Orderby
I need the to order results by PUNCH_TS
but retain the grouping of TYPE_CD
.我需要的订货结果通过
PUNCH_TS
但保留的分组TYPE_CD
。
Query:询问:
select TYPE_CD, PUNCH_TS
from PUNCH
group by PUNCH_TS, TYPE_CD
order by TYPE_CD, PUNCH_TS asc
Result:结果:
ADM 2020-01-13 12:00:00.0
ADM 2020-01-13 17:00:00.0
REG 2020-01-13 08:00:00.0
REG 2020-01-13 12:00:00.0
I changed the order by from the TYPE_CD
to PUNCH_TS
but then it loses the grouping of TYPE_CD
:我将顺序从
TYPE_CD
为PUNCH_TS
但随后它丢失了TYPE_CD
的分组:
REG 2020-01-13 08:00:00.0
ADM 2020-01-13 12:00:00.0
REG 2020-01-13 12:00:00.0
ADM 2020-01-13 17:00:00.0
What I need is:我需要的是:
REG 2020-01-13 08:00:00.0
REG 2020-01-13 12:00:00.0
ADM 2020-01-13 12:00:00.0
ADM 2020-01-13 17:00:00.0
This should do it:这应该这样做:
order by TYPE_CD desc, PUNCH_TS
Rationale: if you want TYPE_CD
'REG'
to appear before 'ADM'
, then you need to a descending sort.基本原理:如果您希望
TYPE_CD
'REG'
出现在'ADM'
之前,那么您需要进行降序排序。 The second sort criteria is ascending PUNCH_TS
, so you get results ordered by ascending timestamp within groups having the same TYPE_CD
.第二个排序标准是升序
PUNCH_TS
,因此您可以在具有相同TYPE_CD
组内按升序时间戳排序的结果。
Edit编辑
If you want the TYPE_CD
that has the earlier timestamp first, then you can use window functions:如果您希望
TYPE_CD
具有较早的时间戳,那么您可以使用窗口函数:
order by min(PUNCH_TS) over(partition by TYPE_CD), PUNCH_TS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.