我有一个返回一系列对象的表。这是示例结果的一小部分(在JSON中):
查询:
SELECT id, starttime, endtime, duration, type FROM things
结果:
{
"id": 3,
"starttime": "2016-09-15T03:27:09",
"endtime": "2016-09-15T03:31:43",
"duration": 274,
"type": "bad"
},
{
"id": 2,
"starttime": "2016-09-15T03:26:48",
"endtime": "2016-09-15T03:27:09",
"duration": 20,
"status": "good"
},
{
"id": 1,
"starttime": "2016-09-15T03:19:46",
"endtime": "2016-09-15T03:26:48",
"duration": 422,
"status": "bad"
},
我试图排除少于30秒的任何事情 - 这很简单。但是,我还需要将前两个组合在一起 - 它们的持续时间相结合,starttime
与id 1' s starttime
和endttime
组合为id 3' s {{1} }。所以这个:
endtime
这在Postgres / SQL中是否可行?我想我可以在Java / C#中找到一些东西,但宁愿在查询中做到这一点。
答案 0 :(得分:1)
您可以使用ROW_NUMBER()
:
SELECT MAX(CASE WHEN s.rnk = 1 THEN s.starttime END) as starttime,
MAX(CASE WHEN s.rnk = 2 THEN s.endtime END) as endtime,
SUM(s.duration) as dur,
--You didn't say which status you want
FROM (
SELECT t.*,
ROW_NUMBER() OVER(ORDER BY t.id) as rnk
FROM things t
WHERE t.duration >= 30) s
WHERE s.rnk < 3