在psql中使用Asc offset和desc

时间:2016-10-19 06:45:28

标签: sql postgresql offset

此代码生成此

SELECT "End_Date"+5                                                   
                FROM exhibits e, rooms r, PlaceOfExhibition p
                WHERE "End_Date">CURRENT_DATE+5 AND r."Minimum" >= 7 and
r."Maximum" <= 16 and p."Location"=r."Name" and e."Name" = p."Exhibition" ORDER
BY "End_Date" desc;
  ?column?  
------------
 2017-01-15
 2016-12-20
 2016-10-22
 2016-09-20
(2 rows)

我需要2016-12-20日期(第二大日期),我并不总是需要第二大日期,但它取决于房间的数量是多少(如果房间查询返回4则我需要第四大一) 我需要从子查询中获取此信息 这是我的子查询

SELECT "End_Date"+5                                                   
                FROM exhibits e, rooms r, PlaceOfExhibition p
                WHERE "End_Date">CURRENT_DATE+5 AND r."Minimum" >= 7 and
r."Maximum" <= 16 and p."Location"=r."Name" and e."Name" = p."Exhibition" ORDER
BY "End_Date" ASC OFFSET (Select Count("Name")-1 FROM Rooms Where "Minimum">=7
and "Maximum"<=16) LIMIT 1 ;

返回此

2016-10-22

所以我的查询得到第二个最后日期,但方向错误,它是第二个最小而不是第二个

2 个答案:

答案 0 :(得分:1)

SELECT "End_Date"+5                                                   
                FROM exhibits e, rooms r, PlaceOfExhibition p
                WHERE "End_Date">CURRENT_DATE+5 AND r."Minimum" >= 7 and
r."Maximum" <= 16 and p."Location"=r."Name" and e."Name" = p."Exhibition" ORDER
BY "End_Date" DESC OFFSET (Select Count("Name")-1 FROM Rooms Where "Minimum">=7
and "Maximum"<=16) LIMIT 1 ;

答案 1 :(得分:-1)

您可以这样做以重新排序结果:

SELECT * FROM
(
    SELECT "End_Date"+5                                                   
    FROM exhibits e, rooms r, PlaceOfExhibition p
    WHERE "End_Date">CURRENT_DATE+5
    AND r."Minimum" >= 7
    AND r."Maximum" <= 16
    AND p."Location"=r."Name"
    AND e."Name" = p."Exhibition"
    ORDER BY "End_Date" desc
) x
ORDER BY 1 asc;