每组最多2行的行组

问题描述 投票:-1回答:2

我有一个像以下http://sqlfiddle.com/#!18/149382/2的数据集

结果应如下所示

TripGroup  Grouper1      Grouper2      Date         Hour              Code    Description
1          6EA579BEA901  58639247D5CB  2018-02-03   00:01:00.0000000  3962X1  GARAG EXTRA
1          6EA579BEA901  58639247D5CB  2018-02-03   00:03:00.0000000  3962X2  RET  EXTRA/GARAG
2          6EA579BEA901  58639247D5CB  2018-02-03   05:45:00.0000000  3962X1  GARAG EXTRA
2          6EA579BEA901  58639247D5CB  2018-02-03   07:30:00.0000000  3962X2  RET  EXTRA/GARAG
3          6EA579BEA901  58639247D5CB  2018-02-03   05:55:00.0000000  3962X1  GARAG EXTRA
3          6EA579BEA901  58639247D5CB  2018-02-03   07:30:00.0000000  3962X2  RET  EXTRA/GARAG
4          6EA579BEA901  58639247D5CB  2018-02-03   14:45:00.0000000  3962X1  GARAG EXTRA
4          6EA579BEA901  58639247D5CB  2018-02-03   15:40:00.0000000  3962X2  RET  EXTRA/GARAG

我的问题是当2个GARAG在RET之前启动时

所有组都应该有一行以GARAGE开头,一行有RET

sql sql-server
2个回答
1
投票

我猜这是你想要的。您还可以将where子句中的Description更改为Code。但如果没有,请告诉我并寻找答案。希望这可以帮助。谢谢。

 SELECT row_number() over (partition by Grouper1, Grouper2 order by Date, Hour) as TripGroup,
  Grouper1,
  Grouper2,
  Date,
  Hour,
  Code,
  Description
FROM FOO
where Description = 'GARAG EXTRA'
UNION ALL
SELECT row_number() over (partition by Grouper1, Grouper2 order by Date, Hour) as TripGroup,
  Grouper1,
  Grouper2,
  Date,
  Hour,
  Code,
  Description
FROM FOO
where Description = 'RET  EXTRA/GARAG'
order by TripGroup, Description;

Result:
TripGroup  Grouper1      Grouper2      Date         Hour              Code    Description
1          6EA579BEA901  58639247D5CB  2018-02-03   00:01:00.0000000  3962X1  GARAG EXTRA
1          6EA579BEA901  58639247D5CB  2018-02-03   00:03:00.0000000  3962X2  RET  EXTRA/GARAG
2          6EA579BEA901  58639247D5CB  2018-02-03   05:45:00.0000000  3962X1  GARAG EXTRA
2          6EA579BEA901  58639247D5CB  2018-02-03   07:30:00.0000000  3962X2  RET  EXTRA/GARAG
3          6EA579BEA901  58639247D5CB  2018-02-03   05:55:00.0000000  3962X1  GARAG EXTRA
3          6EA579BEA901  58639247D5CB  2018-02-03   07:30:00.0000000  3962X2  RET  EXTRA/GARAG
4          6EA579BEA901  58639247D5CB  2018-02-03   14:45:00.0000000  3962X1  GARAG EXTRA
4          6EA579BEA901  58639247D5CB  2018-02-03   15:40:00.0000000  3962X2  RET  EXTRA/GARAG

0
投票

如果你想要一个以GARAGE开头的行和一个带RET的行,那么这个怎么样?

select f.*
from (select f.*,
             row_number() over (partition by grouper1, grouper2, date, datepart(hour, hour), description
                                order by date, hour
                               ) as seqnum 
      from foo f
     ) f
where seqnum = 1
order by grouper1, grouper2, date, datepart(hour, hour),
         (case when description like 'GARAG%' then 1 else 2 end)
© www.soinside.com 2019 - 2024. All rights reserved.